Python的os模块提供了与操作系统交互的功能,其中就包括了文件和目录的管理。下面我将详细介绍os模块中与文件和目录操作相关的方法,并通过代码示例来演示如何使用它们。
1. 目录操作
1.1 获取当前工作目录
使用os.getcwd()可以获取当前Python脚本的工作目录。
python
|
import os |
|
current_dir = os.getcwd() |
|
print("当前工作目录:", current_dir) |
1.2 切换工作目录
使用os.chdir(path)可以切换当前工作目录到指定的路径。
python
|
import os |
|
os.chdir("/path/to/directory") |
|
print("切换后的工作目录:", os.getcwd()) |
1.3 创建目录
使用os.makedirs(path, exist_ok=False)可以递归地创建目录。如果exist_ok设置为True,则目录已存在时不会抛出异常。
python
|
import os |
|
os.makedirs("/path/to/new/directory", exist_ok=True) |
1.4 删除目录
使用os.rmdir(path)可以删除空目录,而os.removedirs(path)则可以递归地删除空目录。
python
|
import os |
|
# 删除空目录 |
|
os.rmdir("/path/to/empty/directory") |
|
|
|
# 递归删除空目录 |
|
os.removedirs("/path/to/empty/directory/tree") |
注意:如果目录不为空,上述方法会抛出异常。可以使用shutil.rmtree(path)来删除非空目录。
1.5 列出目录内容
使用os.listdir(path)可以列出指定目录的内容(文件和子目录名)。
python
|
import os |
|
contents = os.listdir("/path/to/directory") |
|
print("目录内容:", contents) |
2. 文件操作
2.1 文件的路径名操作
·
os.path.join(path, *paths): 将一个或多个路径组件组合起来。
·
os.path.split(path): 将路径分割为目录名和文件名两部分。
·
os.path.dirname(path): 返回指定文件或目录的路径名(不包括文件名)。
·
os.path.basename(path): 返回指定文件或目录的文件名。
·
os.path.exists(path): 检查路径是否存在。
·
os.path.isfile(path): 检查路径是否为文件。
·
os.path.isdir(path): 检查路径是否为目录。
·
os.path.getsize(path): 返回指定文件的大小(以字节为单位)。
·
python
|
import os |
|
|
|
# 路径名操作 |
|
full_path = os.path.join("/path", "to", "file.txt") |
|
print("完整路径:", full_path) |
|
|
|
dir_name, file_name = os.path.split(full_path) |
|
print("目录名:", dir_name) |
|
print("文件名:", file_name) |
|
|
|
print("是否为文件:", os.path.isfile(full_path)) |
|
print("是否为目录:", os.path.isdir(dir_name)) |
|
print("文件大小:", os.path.getsize(full_path)) |
2.2 读取和写入文件
虽然os模块提供了许多与文件和目录交互的功能,但它本身并不直接用于读取或写入文件内容。这通常通过内置的open()函数来实现。
python
|
# 写入文件 |
|
with open("file.txt", "w") as f: |
|
f.write("Hello, world!") |
|
|
|
# 读取文件 |
|
with open("file.txt", "r") as f: |
|
content = f.read() |
|
print("文件内容:", content) |
2.3 复制、移动和删除文件
·
虽然os模块没有直接提供复制和移动文件的方法,但可以使用shutil模块来实现这些功能。
·
·
使用os.remove(path)可以删除文件。
·
python
|
import shutil |
|
import os |
|
|
|
# 复制文件 |
|
shutil.copy("source.txt", "destination.txt") |
|
|
|
# 移动文件(重命名) |
|
shutil.move("source.txt", "new_location.txt") |
|
|
|
# 删除文件 |
|
os.remove("file_to_delete.txt") |
3. 文件和目录的权限
· os.chmod(path, mode): 更改文件或目录的