使用具有完整文件夹结构的python复制文件



几天后我将用一个更好的SSD切换我的SSD,上面存储了一堆数据,如果删除,我可能会后悔。我唯一需要的文件类型是PDF文件、docx文件、txt文件和其他文件。因此,我编写了一个脚本来使用python定位这些文件。

# to copy all of my documents into another location.
import sys
import os
import time
import pathlib
import json

filePath=["D:\", "C:\Users"]
# ext=['mkv','docx','doc','pdf','mp4','zip',]
fileExt=["***.docx","***.doc","***.pdf"]
fileList={}
for each_drive in filePath:
fileList[each_drive]={}
for each_type in fileExt:
fileList[each_drive][each_type]=list(pathlib.Path(each_drive).glob(each_type))
file1 = open('test.txt', 'w')
for each in fileList.values():
for each2 in each.values():
for entry in each2:
print(entry)
file1.writelines(str(str(entry)+ "n"))

file1.close()

这个脚本只定位格式与FileExt列表匹配的文件,并将这些位置写入test.txt文件。现在我需要传输这些文件,同时保持精确的目录结构。例如,如果有一个文件作为

C:Users<MyUser>AppDataLocalFilesS01Attachmentshpe[4].docx

脚本应将整个目录结构复制为

<BackupDrive>:<BackupFolderName>CUsers<MyUser>AppDataLocalFilesS01Attachmentshpe[4].docx

如何使用这种精确的结构进行复制
TLDR:需要复制文件,同时使用Python保持目录结构
P.S.我使用的是Windows,带有Python 3.8

对于文件列表中的每一行,执行以下操作:

for filePath in fileList:
destination = .join(['<BackupDrive>:<BackupFolderName>', filePath[2:]])
os.makedirs(os.path.dirname(filePath), exist_ok=True)
shutil.copy(filePath , destination)

由于您能够将数据写入文件,我假设您也知道如何从该文件中读取数据。然后对于每一行(比如说在该文件中称其为source),使用shutil.copyfile(source, dest).

您可以通过操作source:来创建dest字符串

# remove 'C:'
str_split = source[2:]
# add backup drive and folder
dest = ''.join(['<BackupDrive>:<BackupFolderName>', str_split])

正如评论中提到的,目标路径不会自动创建,但可以像这里解释的那样处理:为shutil.copy文件创建目标路径

感谢@Emmo和@FloLie的回答。我只需要使用os.makedirs()函数,并为列表中的每个文件设置exist_ok标志为true。

这是紧接在问题中的代码之后的代码。

#######################################
# create destination directory
file1=open ('test.txt', 'r')
text= file1.readlines()
# print(text)
for each in text:
each=each[:-1]
destination="BackupDIR-"+each[0]+each[2:]
os.makedirs(os.path.dirname(destination), exist_ok=True)
shutil.copy(each,destination)

这使得整个代码看起来像:

# to copy all of my documents into another location.
import os
import time
import pathlib
import json
import shutil

filePath=["D:\", "C:\Users"]
# ext=['mkv','docx','doc','pdf','mp4','zip',]
fileExt=["***.docx","***.doc","***.pdf"]
fileList={}
for each_drive in filePath:
fileList[each_drive]={}
for each_type in fileExt:
fileList[each_drive][each_type]=list(pathlib.Path(each_drive).glob(each_type))
file1 = open('test.txt', 'w')
for each in fileList.values():
for each2 in each.values():
for entry in each2:
print(entry)
file1.writelines(str(str(entry)+ "n"))
file1.close()
#######################################
# create destination directory
file1=open ('test.txt', 'r')
text= file1.readlines()
# print(text)
for each in text:
each=each[:-1]
destination="BackupDIR-"+each[0]+each[2:]
os.makedirs(os.path.dirname(destination), exist_ok=True)
shutil.copy(each,destination)

附言:这个答案只适用于像我这样的人,他们无法理解断章取义的小片段,有时是

最新更新