【发布时间】:2020-02-04 11:42:21
【问题描述】:
我有一个 python 脚本,它必须首先检查文件夹是否存在于给定路径中,如果存在则删除现有的,然后从源中复制新的。如果不存在,只需复制新文件夹即可。
问题是在源路径中,如果我有文件夹,系统将检查该文件夹是否存在于目标中,如果存在则删除并复制。
我想要的是只检查一个文件夹名称“test”,然后如果不存在则复制新文件夹,如果存在则删除并复制。
代码:
import os
import shutil
from os import path
import datetime
src = "I:/"
src2 = "I:/test"
dst = "C:/Users/LT GM/Desktop/test/"
dst2 = "C:/Users/LT GM/Documents/"
dst3 = "C:/Users/LT GM/Documents/Visual Studio 2017"
def main():
copy()
def copy():
#go through the src files and folders
for root,dirs,files in os.walk(src):
try:
for folder in dirs:
#return folder name
full_folder_name = os.path.join(src, folder)
print("folder : ",full_folder_name)
#check if folder exits
if os.path.exists(dst):
print("folder exist")
#delete folder
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:
print("folder does Not Exist")
#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))
except Exception as e:
print(e)
try:
for name in files:
full_file_name = os.path.join(src, name)
print("files: ",full_file_name)
#check for pdf extension
if name.endswith("pdf"):
#copy files
shutil.copy(full_file_name, dst2)
#check for doc & docx extension
elif name.endswith("docx") or name.endswith("doc"):
#copy files
shutil.copy(full_file_name, dst3)
print("word files done")
print("pdf files done")
except Exception as e:
print(e)
if __name__=="__main__":
main()
【问题讨论】:
-
您不必检查目录是否存在,它会在您的
except中打印错误