亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

精通 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

  1. 树莓派与 Python 构建远程温度传感器:分步实战指南
  2. 树莓派与Python构建机器人:完整指南
  3. C++ 动态内存管理:new 与 delete 专家级实战指南
  4. Python关键字与标识符:掌握保留字与命名规范
  5. Python语句、缩进与注释:清晰指南
  6. Python变量、常量与字面量完全指南
  7. 精通Python类型转换与强制转换:综合指南
  8. 精通Python输入输出与模块导入:实战指南
  9. 理解Python全局、局部与非局部变量
  10. 精通 Python 数字、类型转换与数学运算
  11. 精通 Python 错误与内置异常
  12. Python 获取当前日期和时间:实用指南