写一些关于os模块的代码
时间: 2024-03-28 19:16:49 浏览: 11
以下是几个关于os模块的代码示例:
1. 获取当前工作目录
```python
import os
current_dir = os.getcwd()
print(current_dir)
```
2. 创建新目录
```python
import os
new_dir_name = "new_directory"
os.mkdir(new_dir_name)
```
3. 列出目录中的所有文件
```python
import os
dir_path = "/path/to/directory"
files = os.listdir(dir_path)
for file in files:
print(file)
```
4. 检查文件是否存在
```python
import os
file_path = "/path/to/file"
if os.path.exists(file_path):
print("File exists!")
else:
print("File does not exist.")
```
5. 删除文件
```python
import os
file_path = "/path/to/file"
os.remove(file_path)
```
6. 获取环境变量
```python
import os
home_dir = os.getenv("HOME")
print(home_dir)
```
7. 运行操作系统命令
```python
import os
os.system("ls -l")
```
8. 获取文件的元数据
```python
import os
file_path = "/path/to/file"
file_stat = os.stat(file_path)
print("File size:", file_stat.st_size)
print("Last modified:", file_stat.st_mtime)
```