python 中os库最全最详细的用法
时间: 2023-06-13 12:04:27 浏览: 118
os库是Python中用于与操作系统进行交互的标准库之一。它提供了很多方法来处理文件和目录等操作系统相关的任务。以下是os库中最常用的方法及其用法:
1.获取当前工作目录
```python
import os
current_directory = os.getcwd()
print(current_directory)
```
2.列出指定目录下的所有文件和子目录
```python
import os
path = '/path/to/directory'
files = os.listdir(path)
for file in files:
print(file)
```
3.检查文件或目录是否存在
```python
import os
path = '/path/to/file_or_directory'
if os.path.exists(path):
print('File or directory exists')
else:
print('File or directory does not exist')
```
4.创建目录
```python
import os
path = '/path/to/new_directory'
os.mkdir(path)
```
5.删除文件或目录
```python
import os
path = '/path/to/file_or_directory'
os.remove(path) # 删除文件
os.rmdir(path) # 删除目录
```
6.重命名文件或目录
```python
import os
old_path = '/path/to/old_file_or_directory'
new_path = '/path/to/new_file_or_directory'
os.rename(old_path, new_path)
```
7.获取文件大小
```python
import os
path = '/path/to/file'
size = os.path.getsize(path)
print(size)
```
8.获取文件创建时间和修改时间
```python
import os
import datetime
path = '/path/to/file'
creation_time = os.path.getctime(path)
modification_time = os.path.getmtime(path)
print('Creation time: {}'.format(datetime.datetime.fromtimestamp(creation_time)))
print('Modification time: {}'.format(datetime.datetime.fromtimestamp(modification_time)))
```
这些是os库中最常用的方法,但还有许多其他方法可供使用。可以参考Python官方文档以获取更多信息:https://docs.python.org/3/library/os.html
阅读全文