diatomym diatomym - 7 days ago 5
Python Question

My Python script ignores files while copying

Basically what I want to do in my script is copy some files from dest_path to source_path. You can set it up and see how it works -

But for some reason it copies the first file and tells me that the rest is already copied, which is not true. Is there something that I'm not seeing or that I did wrong? im pretty new to python so sorry if I did something obviously wrong, I just cant see it...

import time, shutil, os, datetime

source_path = r"C:\SOURCE" # Your Source path
dest_path = r"C:\DESTINATION" # Destination path
file_ending = '.txt' # Needed File ending
files = os.listdir(source_path) # defines
date = datetime.datetime.now().strftime('%d.%m.%Y') # get the current date

while True:
print("Beginning checkup")
print("=================")
if not os.path.exists(source_path or dest_path): # checks if directory exists
print("Destination/Source Path does not exist!")
else:
print("Destination exists, checking files...")
for f in files:
if f.endswith(file_ending):
new_path = os.path.join(dest_path, date, )
src_path = os.path.join(source_path, f)
if not os.path.exists(new_path): # create the folders if they dont already exists
print("copying " + src_path)
os.makedirs(new_path)
shutil.copy(src_path, new_path)
else:
print( src_path + " already copied")
# shutil.copy(src_path, new_path)

print("=================")
print('Checkup done, waiting for next round...')
time.sleep(10) # wait a few seconds between looking at the directory

Answer

Like @user2357112 mentioned if not os.path.exists(source_path or dest_path) is not doing what you think. Change to

if not os.path.exists(source_path) or not os.path.exists(dest_path):

This will only copy one file because it creates the directory new_path the first time through in the if. Something like this should work:

if f.endswith(file_ending):
    new_path = os.path.join(dest_path, date, )
    src_path = os.path.join(source_path, f)
    if not os.path.exists(new_path): # create the folders if they dont already exists
        os.makedirs(new_path)
    if not os.path.exists(os.path.join(new_path,f)):
        print("copying " + src_path)
        shutil.copy(src_path, os.path.join(new_path,f))
    else:
        print( src_path + "  already copied")

If the new_path directory doesn't exist then make the directory (this should only happen once and this if could be moved outside of the loop as well as new_path initialization). In a separate if check if the file exists inside that directory and if not copy the file to the location, else print your message.