Python Forum
Help copying files with shutil - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Help copying files with shutil (/thread-20259.html)



Help copying files with shutil - hikerguy62 - Aug-02-2019

I'm messing around with the shutil module (brand new to Python) and trying
to figure out how to copy a file without overwriting it. The below works,
BUT, if I run it multiple times, it overwrites the file (even thought the
except statement is in there).

Also, in the sample I found, they included the word "pass" in the exception. I have it commented out, but what is it for?

source = "C:\\Users\\tom\\Desktop\\testfile1.txt"
target = "C:\\tom\\TESTFOLDER1\\"

try:
    shutil.copy(source, target)
except shutil.SameFileError as e:
     print("File already exists.")
# pass
except IOError as e:
    print("Unable to copy file. %s" % e)
except:
    print("Unexpected error:", sys.exc_info())



RE: Help copying files with shutil - Yoriz - Aug-02-2019

https://docs.python.org/3/library/shutil.html?highlight=shutil#shutil.SameFileError Wrote:exception shutil.SameFileError
This exception is raised if source and destination in copyfile() are the same file.
Raised by copyfile not copy

https://docs.python.org/3/reference/simple_stmts.html#the-pass-statement Wrote:pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed.



RE: Help copying files with shutil - hikerguy62 - Aug-02-2019

I found a workaround using the os module, but I'd still like to know how to check for and handle cases we're I'm copying a file to a directory where that file already exists. And which is better to handle file copying, deleting, etc? The os module or the shutil module?

Here's how I'm doing it using the os module:

import os
import shutil

source = "C:\\Users\\TIM\\Desktop\\testfile1.txt"
target = "C:\\TIM\\TESTFOLDER1\\testfile1.txt"

fileexists = os.path.exists("C:\\TIM\\TESTFOLDER1\\testfile1.txt")
if fileexists:
	print("File not copied. File already exists in destination folder.")
	exit
else: 
    shutil.copy(source, target)