标签云

微信群

扫码加入我们

WeChat QR Code

如果没有文件复制

This question already has an answer here:

I'm fairly new to python, and I'm wondering how I can copy and paste a file from one location to another with first checking to see if the copied file exists in the destination folder?

The reason I want to check if the file exists is this script will be put on a task scheduler and run on a set schedule, so I don't want to be copying everything every single time, just those files that don't exist in the destination folder?

Thanks in advance!


os.path.exists(/some/path/)

2018年06月19日00分31秒

FWIW, I think there's nearly always a better way to handle file creation/deletion/use than os.path.exists. In most cases there's another module that handles it more elegantly (as I used in my answer using glob to compare two lists) and if there's not then try/catch does a better job of preventing the race condition. I can't think of any script I've written that uses os.path.exists that I couldn't re-write to use glob with better functionality.

2018年06月19日00分31秒

adsmith unless you have some security concerns, there's no reason not to use os.path.exist

2018年06月18日00分31秒

Upper-case letters in function and variable names are considered bad style in most Python projects: python.org/dev/peps/pep-0008

2018年06月19日00分31秒

In this case, I don't want to copy an entire folder, I want to copy contents within the folder, PDF files.

2018年06月19日00分31秒

That's what this does -- sorry I was unclear. glob.glob returns a list of the contents of a folder based on some parameters you give it (glob.glob(TARG_DIR+"\\*.pdf") would return a list of files in TARG_DIR with the extension PDF, for instance).

2018年06月19日00分31秒

here is what i've tried and an getting an error: import glob import os.path import shutil SRC_DIR = "C:\\Users\\mboyle\\Documents\\Source" TARG_DIR = "C:\\Users\\mboyle\\Documents\\Target" for file in glob.glob(SRC_DIR): if file not in glob.glob(TARG_DIR): shutil.copy(file,TARG_DIR) else: print "exists"

2018年06月19日00分31秒

What's the error?

2018年06月19日00分31秒

Line 10, which is the shutil.copy(file,TARG_DIR). Do I need to specify a file type (.pdf)?

2018年06月19日00分31秒