os.getcwd() 用来返回当前工作目录
时间: 2023-07-30 12:04:46 浏览: 43
是的,`os.getcwd()` 是 Python `os` 模块中的一个函数,用来返回当前工作目录。该函数没有参数,调用后会返回一个字符串,表示当前 Python 脚本所在的工作目录。需要注意的是,不同操作系统下的工作目录分隔符是不同的,Windows 使用反斜杠 `\`,而 Unix、Linux、macOS 等操作系统使用正斜杠 `/`。因此在编写 Python 程序时,最好使用 `os.path.join()` 等函数来处理路径,以保证程序的可移植性。
相关问题
import os import yaml # 读取yaml的数据 def read_yaml(): with open(os.getcwd()+"/extract.yaml",encoding="utf-8",mode="r") as f: value = yaml.load(f,yaml.FullLoader) return value # 写入数据到yaml文件里面.注意下方的mode,等于a为追加,等于w为清空后重写 def write_yaml(data): with open(os.getcwd()+"/extract.yaml",encoding="utf-8",mode="a") as f: yaml.dump(data,stream=f,allow_unicode=True) # 清空.mode="w" def clear_yaml(): with open(os.getcwd()+"/extract.yaml",encoding="utf-8",mode="w") as f: f.truncate()
这段代码是用来读取和写入 YAML 文件的。具体来说,它包括三个函数:
- `read_yaml()`:用于读取 YAML 文件,返回一个 Python 对象;
- `write_yaml(data)`:用于将 Python 对象写入到 YAML 文件中,参数 `data` 为要写入的 Python 对象;
- `clear_yaml()`:用于清空 YAML 文件。
其中,`yaml.load()` 用于将 YAML 文件转换为 Python 对象,`yaml.dump()` 用于将 Python 对象转换为 YAML 格式并写入文件。`os.getcwd()` 返回当前 Python 脚本所在的目录。
os.chdir(path)
这个函数是用来改变当前的工作目录到指定的路径。其中,path 是一个字符串类型的参数,表示要改变到的目录的路径。如果改变成功,则返回None。下面是一个简单的示例:
```
import os
# 获取当前工作目录
current_dir = os.getcwd()
print("当前工作目录:", current_dir)
# 改变当前工作目录到指定目录
os.chdir('/Users/username/Documents/')
print("当前工作目录:", os.getcwd())
```
运行结果:
```
当前工作目录: /Users/username
当前工作目录: /Users/username/Documents
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)