Python中对文件进行操作
对于Python来说,文件处理绝对是一个常见的处理,读取文件、写入文件、生成文件……文件操作贯穿python
变成始终。
本篇文章将总结一下在平时编程过程中,常用的文件操作。
以下将按照增删改查的顺序,对文件以及目录操作进行总结。
新建文件和目录
import os # 新建文件 new_file_path = "new_file.txt" open(new_file_path, 'w').close() # 创建空文件 # 新建目录 new_dir_path = "new_directory" os.makedirs(new_dir_path) # 创建目录,包括所有必需的中间目录
删除文件和目录
# 删除文件 os.remove(new_file_path) # 删除目录 os.rmdir(new_dir_path) # 删除空目录 # 或者删除目录及其内容 import shutil shutil.rmtree(new_dir_path)
修改文件和目录名
# 修改文件名 new_file_name = "renamed_file.txt" os.rename(new_file_path, new_file_name) # 修改目录名 new_dir_name = "renamed_directory" os.rename(new_dir_path, new_dir_name) # 修改文件格式(扩展名) new_extension = "txt" os.rename(new_file_name, f"{new_dir_name}.{new_extension}") # 修改文件权限 os.chmod(new_file_name, 0o755) # 修改文件权限为755 # 修改目录权限 os.chmod(new_dir_name, 0o755) # 修改目录权限为755
查询文件和目录
# 查询当前目录下的文件和目录 current_directory = os.getcwd() files_in_directory = [f for f in os.listdir(current_directory) if os.path.isfile(os.path.join(current_directory, f))] directories_in_directory = [d for d in os.listdir(current_directory) if os.path.isdir(os.path.join(current_directory, d))] # 判断文件、目录是否存在 if os.path.exists(file_path): print(f"The file '{file_path}' exists.") else: print(f"The file '{file_path}' does not exist.") # 遍历查询目录下所有文件 def list_files(start_path): for root, dirs, files in os.walk(start_path): for file in files: print(os.path.join(root, file))
# 调用遍历函数 list_files(current_directory)
遍历目录还有一个更加方便的函数“walk”
import os start_directory = "your_start_directory" for root, directories, files in os.walk(start_directory): print(f"Current directory: {root}") print(f"Subdirectories: {directories}") print(f"Files: {files}") print("-" * 40)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义