Copy file if it doesn't already exist

This question already has an answer here:

  • How to check whether a file exists? 39 answers

  • In Python, it can often be seen that you will hit errors, known as exceptions , when running code. For this reason, the try/catch has been deployed.

    Here is a snippet of code I use in my day-to-day that clears files from a directory, or skips if they do not exist.

    def DeleteFile(Path_):
        """Deletes saved project AND its corresponding "files" folder."""
        try: #deletes the folder
            os.remove(Path_)
        except OSError:
            pass
        try: #deletes the file, using some fancy python operations to arrive at the filename
            shutil.rmtree(os.path.join(os.path.dirname(Path_),os.path.splitext(os.path.basename(Path_))[0])+"_files", True)
        except OSError:
            pass
    

    This is a classic example of checking for if a file exists. Instead of deleting inside your try statement, you could have try to copy the file. If it fails, it moves on to pass , which just skips the try/catch block.

    Take note, try/catch can be used to catch any exception, or it can be used to catch specific ones. I have OSError scrawled in but read through them to be sure that's the one you want. If you have a specific error in a catch and the system gives back the wrong kind of error, your try/catch will not work the way you want it to. So, be sure. IN best case, be general.

    Happy coding!

    EDIT: It is worth noting that this try/catch system is a very Pythonic way to go about things. try/catch is very easy and popular, but your situation may call for something different.

    EDIT: I'm not sure if it's worth noting this, but I realize my answer doesn't directly tell you how to check if a file exists. Instead, it assumes that it does not and proceeds with the operation anyway. If you hit a problem (ie, it exists and you need to overwrite), you can make it so that it automatically skips over the entire thing and goes onto the next one. Again, this is only one of many methods for accomplishing the same task.


    import glob
    import os.path
    import shutil
    
    SRC_DIR = #your source directory
    TARG_DIR = #your target directory
    
    GLOB_PARMS = "*" #maybe "*.pdf" ?
    
    for file in glob.glob(os.path.join(SRC_DIR,GLOB_PARMS)):
        if file not in glob.glob(os.path.join(SRC_DIR,GLOB_PARMS)):
            shutil.copy(file,TARG_DIR)
        else:
            print("{} exists in {}".format(
                file,os.path.join(os.path.split(TARG_DIR)[-2:]))
            # This is just a print command that outputs to console that the
            # file was already in directory
    

    I'm assuming you're trying to send a whole folder over with this command, otherwise glob uses pretty easy to understand interface. glob.glob *.txt will grab all the files with a .txt extension, etc. Shouldn't be too hard to tweak this to exactly what you want.

    It's important to note that file copy usually involves a race condition. Basically, time passes between checking to see if the file isn't in TARG_DIR ( if file not in glob.glob(TARG_DIR) ) and actually copying it there ( shutil.copy(file,TARG_DIR) ). In that amount of time, the file could end up there, which will cause shutil.copy to overwrite the file. This may not be your intended functionality, in which case you should look into a different method. I don't know of a good one without some research that will try to copy a file but return an exception if that file already exists.

    Try/Except blocks, as another answer mentioned, may be useful here as well if it's possible you won't have write access to the directory when your script runs. shutil.copy will return an IOError exception if that is the case. I believe glob will just return an empty list if you don't have read access to your source directory (which in turn will feed nothing through the "For" loop, so you won't have any errors there).

    EDIT: Apparently glob doesn't work the way I remembered it did, sorry about that.

    链接地址: http://www.djcxy.com/p/7302.html

    上一篇: 在Python中进行文件测试?

    下一篇: 如果文件不存在,请复制文件