[英]How to copy files from one folder to another taking into account that the file name contains the name of the destination folders in python
I need to copy files from a source folder like this:我需要从这样的源文件夹中复制文件:
And paste them into another folders like these:并将它们粘贴到另一个文件夹中,如下所示:
As you can see, the destination folder has subfolders with the 1.1 and 1.2 numerations.如您所见,目标文件夹中包含编号为 1.1 和 1.2 的子文件夹。 (The real folder has too many, for that reason is not possible to do a manual "if" comparison) (真实文件夹太多,因此无法进行手动“如果”比较)
What I need is the python script walk in the Source folder and evaluate each file to determinate in which destiny folder and subfolder it have to put in.我需要的是 python 脚本在 Source 文件夹中走动并评估每个文件以确定它必须放入哪个 destination 文件夹和子文件夹。
For example the files "ABC_1.1_files.zip" and "ABC_1.1_test.xlsx" have to paste into folder "ABC" and in subfolder "1.1" and the same with the another files.例如,文件“ABC_1.1_files.zip”和“ABC_1.1_test.xlsx”必须粘贴到文件夹“ABC”和子文件夹“1.1”中,其他文件也一样。
I really appreciate your help!非常感谢您的帮助!
import os
import shutil
src = "PATH/TO/SOURCE/FOLDER"
dst = "PATH/TO/DESTINATION/FOLDER"
for file_name in os.listdir(src):
sub, num = file_name.split("_")[:2]
new_dst = dst + f"{sub}/{num}/"
os.makedirs(os.path.dirname(new_dst), exist_ok=True)
shutil.copy(src, new_dst)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.