완전한 폴더 구조로 파이썬을 사용하여 파일 복사
며칠 내에 SSD를 더 나은 것으로 전환하고 있으며 삭제하면 후회할 수있는 많은 데이터가 저장되어 있습니다. 필요한 유일한 파일 유형은 PDF 파일, docx 파일, txt 파일 및 기타 파일입니다. 그래서 파이썬을 사용하여 해당 파일을 찾는 스크립트를 작성했습니다.
# 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>\AppData\Local\Files\S0\1\Attachments\hpe[4].docx
스크립트는 전체 디렉토리 구조를 다음과 같이 복사해야합니다.
<BackupDrive>:\<BackupFolderName>\C\Users\<MyUser>\AppData\Local\Files\S0\1\Attachments\hpe[4].docx
이 정확한 구조를 사용하여 어떻게 복사합니까?
TLDR : Python
PS를 사용하는 것처럼 디렉터리 구조를 유지하면서 파일을 복사해야합니다. 저는 Python 3.8과 함께 Windows를 사용하고 있습니다.
답변
파일 목록의 각 행에 대해 다음을 수행하십시오.
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)
.
다음 dest
을 조작 하여 문자열을 만들 수 있습니다 source
.
# remove 'C:'
str_split = source[2:]
# add backup drive and folder
dest = ''.join(['<BackupDrive>:\<BackupFolderName>', str_split])
주석에서 언급했듯이 대상 경로는 자동으로 생성되지 않지만 여기에 설명 된대로 처리 할 수 있습니다. shutil.copy 파일의 대상 경로 생성
답변에 대해 @Emmo 및 @FloLie에게 감사드립니다. 목록의 각 파일에 대해 exist_ok 플래그를 true로 설정하여 os.makedirs () 함수를 사용해야했습니다.
이것은 질문의 코드 바로 뒤에 배치 된 코드입니다.
#######################################
# 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)
추신 :이 답변은 가끔 문맥에서 작은 조각을 이해할 수없는 저와 같은 사람들에게만 있습니다 😁