python os 使用
时间: 2023-05-29 11:06:32 浏览: 41
Python的os模块提供了与操作系统交互的功能,包括文件和目录操作、进程管理、环境变量访问等。
以下是一些常见的os模块操作:
1. 获取当前工作目录
```
import os
print(os.getcwd())
```
2. 改变当前工作目录
```
os.chdir('/path/to/new/directory')
```
3. 列出目录下的文件和子目录
```
print(os.listdir('.'))
```
4. 创建目录
```
os.mkdir('/path/to/new/directory')
```
5. 创建多级目录
```
os.makedirs('/path/to/new/directory')
```
6. 删除文件
```
os.remove('/path/to/file')
```
7. 删除目录
```
os.rmdir('/path/to/directory')
```
8. 删除多级目录
```
os.removedirs('/path/to/directory')
```
9. 重命名文件或目录
```
os.rename('old_file.txt', 'new_file.txt')
```
10. 获取文件或目录的信息
```
print(os.stat('file.txt'))
```
11. 获取环境变量
```
print(os.getenv('PATH'))
```
12. 执行系统命令
```
os.system('ls')
```
以上是一些常用的os模块操作,更多详细的操作可参考Python官方文档。