网站首页 > 技术文章 正文
Python 提供了 os 和 shutil 等内置包,以有效地处理目录和文件。os 软件包提供与操作系统交互的功能,例如创建目录和导航文件系统。shutil 包可用于对文件和文件集合执行高级操作。
创建目录
使用 os.mkdir() 和 os.makedirs() 函数在 Python 中创建目录非常简单。
- 使用 os.mkdir()
import os
# Create a single directory
os.mkdir('new_folder')
使用 os.makedirs()
import os
# Create a directory with nested folders
os.makedirs('parent_folder/child_folder')
如果目录已经存在,这两个函数都会引发错误,因此您可能需要先检查它是否存在:
import os
if not os.path.exists('new_folder'):
os.mkdir('new_folder')
列出目录中的文件
要列出目录中的所有文件,可以使用 os.listdir():
import os
# List all files in the current directory
files = os.listdir('.')
for file in files:
print(file)
对于更复杂的过滤,glob 模块是一个强大的替代方案:
import glob
# List all .txt files in the current directory
txt_files = glob.glob('*.txt')
print(txt_files)
移动和复制文件
shutil 软件包提供了简单的功能来移动和复制文件。
复制文件
import shutil
# Copy a file
shutil.copy('source.txt', 'destination.txt')
移动文件
import shutil
# Move a file
shutil.move('source.txt', 'new_folder/destination.txt')
这些功能很直观,使文件操作变得简单明了。
删除文件和目录
删除文件和目录是有风险的,因此在继续之前,请务必确保您有备份。os.remove() 函数用于文件,而 os.rmdir() 和 shutil.rmtree() 用于目录。
- 删除文件
import os
# Delete a single file
os.remove('file_to_delete.txt')
删除目录
import os
import shutil
# Remove an empty directory
os.rmdir('empty_folder')
# Remove a directory with its contents
shutil.rmtree('folder_to_delete')
结论
了解如何处理目录和文件对于任何 Python 开发人员来说都至关重要。os 和 shutil 软件包提供了强大的工具,可以轻松创建、移动、复制和删除文件和目录。无论您是自动化任务还是构建复杂的系统,这些工具都将非常宝贵
猜你喜欢
- 2025-01-26 Python 3 基础教程 - 文件 I/O(python中文件的基本操作)
- 2025-01-26 有了11个技巧,Python 中的事情会变得很容易!
- 2025-01-26 二十七、深入浅出Python中的 os模块
- 2025-01-26 人生苦短,不光要用 Python,还要在 VSCode 里用 | 原力计划
- 2025-01-26 如何使用 PEP 8 帮助你编写漂亮的 Python 代码
- 2025-01-26 人生苦短,我用Python,初学者最友好的编程语言
- 2025-01-26 【Python核武器】:Numpy深度攻略!(一)
- 2025-01-26 10 分钟干完 2 小时的活,用 Python 自动化办公有多爽?
- 2025-01-26 Python 中sys 模块深度解析:优化代码、调试异常与动态执行
- 2025-01-26 国人开源的异步 Python ORM:GINO(python2 异步)
- 258℃Python短文,Python中的嵌套条件语句(六)
- 258℃python笔记:for循环嵌套。end=""的作用,图形打印
- 257℃PythonNet:实现Python与.Net代码相互调用!
- 252℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 252℃Python实现字符串小写转大写并写入文件
- 108℃原来2025是完美的平方年,一起探索六种平方的算吧
- 91℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 83℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)