# 导入文件处理相关库
import os, shutil
# 遍历函数
def read_dirs(f_path):
# 获取f_path路径下的所有文件及文件夹
paths = os.listdir(f_path)
# 获得目标文件后复制过去的路径
target_path = r"D:\target"
# 判断
for f_name in paths:
com_path = f_path + "\\" + f_name
if os.path.isdir(com_path): # 如果是一个文件夹
read_dirs(com_path) # 递归调用
if os.path.isfile: # 如果是一个文件
try:
suffix = com_path.split(".")[1] # suffix=后缀(获取文件的后缀)
except Exception as e:
continue # 对于没有后缀的文件省略跳过
try:
# 可以根据自己需求,修改不同的后缀以获得该类文件
if suffix == "pdf" or suffix == "PDF": # 获取pdf文件
shutil.copy(com_path, target_path)
elif suffix == "docx" or suffix == "DOCX": # 获取docx文件
shutil.copy(com_path, target_path)
elif suffix == "jpg" or suffix == "JPG": # 获取jpg文件
shutil.copy(com_path, target_path)
elif suffix == "png" or suffix == "PNG": # 获取png文件
shutil.copy(com_path, target_path)
elif suffix == "xlsx" or suffix == "XLSX": # 获取xlsx文件
shutil.copy(com_path, target_path)
elif suffix == "mp4" or suffix == "MP4": # 获取mp4文件
shutil.copy(com_path, target_path)
else:
continue
except Exception as e:
print(e)
continue
if __name__ == "__main__":
f_path = r"D:\技术学习\Python" # 需要遍历的文件路径
read_dirs(f_path) # 调用函数
Python 递归遍历文件夹(子文件夹及其所有文件),获取图片,docx,pdf等
最新推荐文章于 2024-07-22 04:45:00 发布