[英]Python 3 - Copy files if they do not exist in destination folder
I am attempting to move a couple thousand pdfs from one file location to another.我试图将几千个 pdf 从一个文件位置移动到另一个文件位置。 The source folder contains multiple subfolders and I am combining just the pdfs (technical drawings) into one folder to simplify searching for the rest of my team.源文件夹包含多个子文件夹,我仅将 pdf(技术图纸)合并到一个文件夹中,以简化对团队其他成员的搜索。
The main goal is to only copy over files that do not already exist in the destination folder.主要目标是仅复制目标文件夹中尚不存在的文件。 I have tried a couple different options, most recently what is shown below, and in all cases, every file is copied every time.我尝试了几个不同的选项,最近的选项如下所示,在所有情况下,每次都会复制每个文件。 Prior to today, any time I attempted a bulk file move, I would received errors if the file existed in the destination folder but I no longer do.在今天之前,每当我尝试批量移动文件时,如果文件存在于目标文件夹中,我都会收到错误消息,但我不再这样做了。
I have verified that some of the files exist in both locations but are still being copied.我已经确认有些文件存在于两个位置,但仍在被复制。 Is there something I am missing or can modify to correct?有什么我遗漏或可以修改以纠正的吗?
Thanks for the assistance.感谢您的帮助。
import os.path
import shutil
source_folder = os.path.abspath(r'\\source\file\location')
dest_folder = os.path.abspath(r'\\dest\folder\location')
for folder, subfolders, files in os.walk(source_folder):
for file in files:
path_file=os.path.join(folder, file)
if os.path.exists(file) in os.walk(dest_folder):
print(file+" exists.")
if not os.path.exists(file) in os.walk(dest_folder):
print(file+' does not exist.')
shutil.copy2(path_file, dest_folder)
os.path.exists
returns a Boolean value. os.path.exists
返回一个布尔值。 os.walk
creates a generator which produces triples of the form (dirpath, dirnames, filenames)
. os.walk
创建一个生成器,该生成器生成(dirpath, dirnames, filenames)
形式的三元组。 So, that first conditional will never be true.因此,第一个条件永远不会为真。
Also, even if that conditional were correct, your second conditional has a redundancy since it's merely the negation of the first.此外,即使该条件是正确的,您的第二个条件也有冗余,因为它只是第一个的否定。 You could replace it with else
.你可以用else
替换它。
What you want is something like你想要的是类似的东西
if file in os.listdir(dest_folder):
...
else:
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.