Как мне скопировать каталог в python? - PullRequest
0 голосов
/ 05 февраля 2020

У меня есть код, который копирует папки и файлы по заданному пути, который включает файлы pdf и файлы слова и папка, которая также включает файлы pdf .

мне нужно скопировать каждый файл в другое место назначения.

  • файл pdf по назначению a
  • файл слова по назначению b
  • папка и подкаталоги адресата c

проблема в том, что у адресата a будут файлы pdf и файлы подкаталогов которые находятся в папке. Тем не менее, в папке назначения c также будет правильно скопирована папка.

, поэтому проблема заключается в месте назначения a

Это структура У меня есть в I:

I:
├── file1.doc
├── file1.pdf
├── file2.pdf
└── folder1
    ├── file3.pdf
    └── file4.pdf

Результат должен быть:

├── A
│   ├── file1.pdf
│   └── file2.pdf
├── B
│   └── file1.doc
└── C
    └── folder1
        ├── file3.pdf
        └── file4.pdf

На данный момент результат:

├── A
│   ├── file1.pdf
│   ├── file2.pdf
│   ├── file3.pdf
│   └── file4.pdf
├── B
│   └── file1.doc
└── C
    └── folder1
        ├── file3.pdf
        └── file4.pdf

И это код, который я ' м с использованием:

import os
import shutil
from os import path

src = "I:/"
src2 = "I:/test"

dst = "C:/Users/xxxx/Desktop/test/"
dst2 = "C:/Users/xxxxx/Documents/"
dst3 = "C:/Users/xxxxx/Documents/Visual Studio 2017"

def main():
    copy()

def copy():
    i = 0
    j = 0
    for dirpath, dirnames, files in os.walk(src):

        print(f'Found directory: {dirpath}')
        # for file_name in files:
        if len(dirnames)==0 and len(files)==0:
                print("this directory is empty")
        else:
            print(files)

        for name in files:

            full_file_name = os.path.join(dirpath, name)
            #check for pdf extension
            if name.endswith("pdf"):
                i=i+1
                #copy files
                shutil.copy(full_file_name, dst2)
                #check for doc & docx extension 
            elif name.endswith("docx") or name.endswith("doc"):
                j=j+1
                #copy files
                shutil.copy(full_file_name, dst3)
                # print(i,"word files done")
        print("{0} pdf files".format(i))
        print("{0} word files".format(j))


    # except Exception as e:
        # print(e)
    if os.path.exists(dst): 
        shutil.rmtree(dst)
        print("the deleted folder is :{0}".format(dst))
        #copy the folder as it is (folder with the files)
        copieddst = shutil.copytree(src2,dst)
        print("copy of the folder is done :{0}".format(copieddst))
    else:
        #copy the folder as it is (folder with the files)
        copieddst = shutil.copytree(src2,dst)
        print("copy of the folder is done :{0}".format(copieddst))

if __name__=="__main__":
    main()

1 Ответ

0 голосов
/ 05 февраля 2020

Вот простое решение в Python 3.4+ (из-за pathlib):

from pathlib import Path

src = Path('I:/')

pdfs = Path('I:/test')
docs = Path('C:/Users/xxxxx/Documents')
dirs = Path('C:/Users/xxxxx/Documents/Visual Studio 2017')

suffixes = {
    'docs': ['.doc', '.docx'],
    'pdfs': ['.pdf']
}


def main():
    for o in src.glob('*'):
        if o.is_dir():
            o.rename(dirs / o.name)

        if o.is_file():
            if o.suffix in suffixes['docs']:
                o.rename(docs / o.name)
            elif o.suffix in suffixes['pdfs']:
                o.rename(pdfs / o.name)


if __name__ == '__main__':
    main()
...