我有一个代码,可以从给定路径中复制文件夹和文件,该路径包括pdf文件和word文件和包括pdf文件的文件夹。
我需要将每个副本复制到不同的目的地均值
问题是目标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()
这是Python 3.4+中的一个简单解决方案:
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')
def main():
for o in src.glob('*'):
if o.is_dir():
o.rename(dirs / o.name)
if o.is_file():
if o.suffix in ('.doc', 'docx'):
o.rename(docs / o.name)
elif o.suffix in ('.pdf'):
o.rename(pdfs / o.name)
if __name__ == '__main__':
main()