精通 Python 目录与文件操作
Python 目录与文件管理
通过清晰的实战示例,学习如何在 Python 中高效创建、导航、列出、重命名和删除目录与文件。
视频:Python os 模块
Python 目录
项目增长时,将代码组织到结构良好的文件夹变得至关重要。目录——或文件夹——是文件和子目录的容器,Python 的 os 模块提供强大工具管理它们。
获取当前目录
用 os.getcwd() 获取当前工作目录字符串。若需字节表示,os.getcwdb() 可用。
import os
os.getcwd() # 'C:\\Program Files\\PyScripter'
os.getcwdb() # b'C:\\Program Files\\PyScripter'
双反斜杠表示转义序列。用 print() 可正确渲染路径:
print(os.getcwd()) # C:\Program Files\PyScripter
更改目录
用 os.chdir(path) 切换当前工作目录。path 参数可用正斜杠或反斜杠;只需转义反斜杠或用原始字符串。
os.chdir('C:\\Python33')
print(os.getcwd()) # C:\Python33
列出目录和文件
用 os.listdir(path) 获取目标文件夹下所有文件和子目录。省略 path 则操作当前工作目录。
print(os.getcwd()) # C:\Python33
os.listdir() # ['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'Scripts', 'tcl', 'Tools']
os.listdir('G:\\') # ['$RECYCLE.BIN', 'Movies', 'Music', 'Photos', 'Series', 'System Volume Information']
创建新目录
用 os.mkdir(path) 创建文件夹。若路径为相对路径,新目录出现在当前工作目录下。
os.mkdir('test')
print(os.listdir()) # ['test']
重命名目录或文件
os.rename(src, dst) 同一函数处理文件和文件夹。src 为旧名,dst 为新名:
os.listdir() # ['test']
os.rename('test', 'new_one')
print(os.listdir()) # ['new_one']
删除目录或文件
用 os.remove(path) 删除文件。删除空文件夹用 os.rmdir(path):
os.listdir() # ['new_one', 'old.txt']
os.remove('old.txt')
print(os.listdir()) # ['new_one']
os.rmdir('new_one')
print(os.listdir()) # []
注意:os.rmdir() 仅适用于空目录。
若需删除包含文件或子文件夹的文件夹,用 shutil 模块的 shutil.rmtree():
os.listdir() # ['test']
os.rmdir('test') # Traceback ... OSError: [WinError 145] The directory is not empty: 'test'
import shutil
shutil.rmtree('test')
print(os.listdir()) # []
Python