问题描述
我有一堆PDF,这些报告是由名为00002755、0002758、00002760等系统生成的报告。
我已经有一个完全按照00002755、00002758、00002760等命名的文件夹...等等。
我要实现的是将PDF文件“ 00002755.pdf”剪切并粘贴到名为“ 00002755”的文件夹中
此刻我的文件夹如下:
结论是,当我运行python脚本时,所有pdf都将进入各自的文件夹中。
解决方法
可以使用不同的模块以不同的方式来完成它,在这里我将仅使用os,它也应该很好并且非常快(永远不要使用大量的文件/目录作为基准,请在需要时随意这样做)完成任务)
import os
curr_dir = os.path.dirname(os.path.realpath(__file__)) # Get current abspath based on your py file name
for i in [f.name for f in os.scandir(curr_dir) if f.is_dir()]: # Iterate through the dirs
for j in [f.name for f in os.scandir(curr_dir) if f.is_file()]: # Iterate through the files
if i == j.split(".pdf")[0]: # If both match each other,move the file with os.rename
os.rename(f"{curr_dir}\\{j}",f"{curr_dir}\\{i}\\{j}")