Python 目录与文件管理:操作、管理与检验详解
本篇文章介绍了如何使用 Python 的 os
和 shutil
库进行文件和目录的操作、管理与检验。通过 os
库中的 getcwd()
、makedirs()
、listdir()
等方法,可以轻松实现目录的创建、删除、重命名等操作,同时也可以进行文件存在性、类型的验证,如使用 isfile()
和 isdir()
方法。文章还涵盖了如何创建、复制文件以及处理包含子目录的文件夹,并提供了详细的代码示例。该指南不仅适合文件的基本管理需求,还涉及高级操作如递归删除目录和处理文件路径拆分等。
一 功能总览
主要涉及os库
中的功能:文件目录操作,文件管理系统,文件目录多种检验。以下列表是相关的函数方法。
文件目录操作 | 文件管理系统 | 文件目录多种检验 |
---|---|---|
os.getcwd() | os.removedirs() | os.path.isfile() |
os.listdir() | shutil.rmtree() | os.path.exists() |
os.makedirs() | os.rename() | os.path.isdir() |
os.path.exists() | os.path.basename() | |
os.path.dirname() | ||
os.path.split() |
二 文件目录操作
# 文件目录操作
print("当前目录:", os.getcwd())
print("当前目录里有什么:", os.listdir())
# 在当前目录新建 project 目录
os.makedirs("project", exist_ok=True)
print(os.path.exists("project"))
三 文件管理系统
# 文件管理系统
# 创建文件夹
if os.path.exists("user/mofan"):
print("user exist")
else:
os.makedirs("user/mofan")
print("user created")
# user 目录下有什么
print(os.listdir("user"))
# 删除文件夹,user会一并删除
if os.path.exists("user/mofan"):
# os.removedirs("user/mofan")
print("user removed")
else:
print("user not exist")
# 文件夹里有文件删除时会报错
os.makedirs("user/mofan01", exist_ok=True)
with open("user/mofan01/a.txt", "w") as f:
f.write("nothing")
# os.removedirs("user/mofan01") # 这里会报错
# 清空整个目录,user 的子目录会被清空,无论存不存文件,慎用
shutil.rmtree("user/mofan01")
print(os.listdir("user"))
# 修改文件夹名字
os.makedirs("user/mofan", exist_ok=True)
# os.rename("user/mofan", "user/mofanpy")
print(os.listdir("user"))
四 文件目录多种检验
定义 copy 和 copyBySplit 函数
def copy(path):
filename = os.path.basename(path) # 文件名
dir_name = os.path.dirname(path) # 文件夹名
new_filename = "new_" + filename # 新文件名
new_path = os.path.join(dir_name, new_filename) # 目录重组
shutil.copy2(path, new_path) # 复制文件
return os.path.isfile(new_path), new_path
def copyBySplit(path):
dir_name, filename = os.path.split(path)
new_filename = "new2_" + filename # 新文件名
new_path = os.path.join(dir_name, new_filename) # 目录重组
shutil.copy2(path, new_path) # 复制文件
return os.path.isfile(new_path), new_path
调用 copy 和 copyBySplit 创建副本
# 文件目录多种检验,判断是否时文件或者目录
os.makedirs("user/mofan", exist_ok=True)
with open("user/mofan/a.txt", "w") as f:
f.write("nothing")
print(os.path.isfile("user/mofan/a.txt")) # True
print(os.path.exists("user/mofan/a.txt")) # True
print(os.path.isdir("user/mofan/a.txt")) # False
print(os.path.isdir("user/mofan")) # True
# 创建一个文件副本
copied, new_path = copy("user/mofanpy01/a.txt")
if copied:
print("copied to:", new_path)
else:
print("copy failed")
# 使用 os.path.split(path) 创建文件副本
copied, new_path = copyBySplit("user/mofanpy02/a.txt")
if copied:
print("copied to:", new_path)
else:
print("copy failed")
五 完整文件示例
# This is a sample Python script.
import os
import shutil
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
def copy(path):
filename = os.path.basename(path) # 文件名
dir_name = os.path.dirname(path) # 文件夹名
new_filename = "new_" + filename # 新文件名
new_path = os.path.join(dir_name, new_filename) # 目录重组
shutil.copy2(path, new_path) # 复制文件
return os.path.isfile(new_path), new_path
def copyBySplit(path):
dir_name, filename = os.path.split(path)
new_filename = "new2_" + filename # 新文件名
new_path = os.path.join(dir_name, new_filename) # 目录重组
shutil.copy2(path, new_path) # 复制文件
return os.path.isfile(new_path), new_path
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press ⌘F8 to toggle the breakpoint.
# 主要涉及到的功能:
# 文件目录操作
# os.getcwd()
# os.listdir()
# os.makedirs()
# os.path.exists()
# 文件管理系统
# os.removedirs()
# shutil.rmtree()
# os.rename()
# 文件目录多种检验
# os.path.isfile()
# os.path.exists()
# os.path.isdir()
# os.path.basename()
# os.path.dirname()
# os.path.split()
# os库
# 文件目录操作
print("当前目录:", os.getcwd())
print("当前目录里有什么:", os.listdir())
# 在当前目录新建 project 目录
os.makedirs("project", exist_ok=True)
print(os.path.exists("project"))
# 文件管理系统
# 创建文件夹
if os.path.exists("user/mofan"):
print("user exist")
else:
os.makedirs("user/mofan")
print("user created")
# user 目录下有什么
print(os.listdir("user"))
# 删除文件夹,user会一并删除
if os.path.exists("user/mofan"):
# os.removedirs("user/mofan")
print("user removed")
else:
print("user not exist")
# 文件夹里有文件删除时会报错
os.makedirs("user/mofan01", exist_ok=True)
with open("user/mofan01/a.txt", "w") as f:
f.write("nothing")
# os.removedirs("user/mofan01") # 这里会报错
# 清空整个目录,user 的子目录会被清空,无论存不存文件,慎用
shutil.rmtree("user/mofan01")
print(os.listdir("user"))
# 修改文件夹名字
os.makedirs("user/mofan", exist_ok=True)
# os.rename("user/mofan", "user/mofanpy")
print(os.listdir("user"))
# 文件目录多种检验,判断是否时文件或者目录
os.makedirs("user/mofan", exist_ok=True)
with open("user/mofan/a.txt", "w") as f:
f.write("nothing")
print(os.path.isfile("user/mofan/a.txt")) # True
print(os.path.exists("user/mofan/a.txt")) # True
print(os.path.isdir("user/mofan/a.txt")) # False
print(os.path.isdir("user/mofan")) # True
# 创建一个文件副本
copied, new_path = copy("user/mofanpy01/a.txt")
if copied:
print("copied to:", new_path)
else:
print("copy failed")
# 使用 os.path.split(path) 创建文件副本
copied, new_path = copyBySplit("user/mofanpy02/a.txt")
if copied:
print("copied to:", new_path)
else:
print("copy failed")
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('文件目录管理')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
复制粘贴并覆盖到你的 main.py 中运行,运行结果如下。
Hi, 文件目录管理
当前目录: /Users/dayu/Documents/openSource/your-python
当前目录里有什么: ['new_file4.txt', 'Function 函数.py', 'new_file5.txt', 'new_file.txt', '其他文件', 'me.py', 'new_file2.txt', '.DS_Store', 'new_file3.txt', 'LICENSE', 'requirements.txt', 'Module 模块.py', 'chinese.txt', 'module', 'user', '数据种类.py', 'README.md', 'project', 'file.py', '.gitignore', '变量与运算.py', '文件目录管理.py', '条件判断.py', 'Class 类.py', '.git', 'main.py', '读写文件.py', 'for 和 while 循环.py', '.idea']
True
user exist
['mofanpy', 'mofanpy02', 'mofanpy01', 'mofan']
user removed
['mofanpy', 'mofanpy02', 'mofanpy01', 'mofan']
['mofanpy', 'mofanpy02', 'mofanpy01', 'mofan']
True
True
False
True
copied to: user/mofanpy01/new_a.txt
copied to: user/mofanpy02/new2_a.txt
六 源码地址
代码地址:
引用 莫烦 Python