Warm tip: This article is reproduced from serverfault.com, please click

Copy files using python with complete folder structure

发布于 2020-11-29 16:04:41

I am switching my SSD with a better one in a few days and I have a bunch of data stored on it that I might regret if deleted. The only type of files I need are PDF files, docx files, txt files and other things. So, I wrote a script to locate those files using 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()

This script just locates the file with formats matching the FileExt list and writes out those locations to test.txt file. Now I need to transfer these files while keeping the exact directory structure. For example, If there is a file as

C:\Users\<MyUser>\AppData\Local\Files\S0\1\Attachments\hpe[4].docx

The script should copy the entire directory structure as

<BackupDrive>:\<BackupFolderName>\C\Users\<MyUser>\AppData\Local\Files\S0\1\Attachments\hpe[4].docx

How do I copy using this exact structure.
TLDR: Need to copy files while keeping the directory structure as is using Python
P.S. I am using Windows, with Python 3.8

Questioner
CrYbAbY
Viewed
0
FloLie 2020-11-30 00:20:11

For each line in your file list, do the following:

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