I have a script that I have almost 100% complete however there is just one more step that I can not figure out. My script currently checks the destination to see if the file already exists and if it does then the file from the source location is not moved over. The problem I am running into is that the code doesn't check all of the subdirectories as well just the root directory.
I am using os.walk to go through all of the files in the source folder but am not sure how to os.walk the destination folder and the source folder in conjunction with each other.
import time
import sys
import logging
import logging.config
def main():
purge_files
def move_files(src_file):
try:
#Attempt to move files to dest
shutil.move(src_file, dest)
#making use of the OSError exception instead of FileExistsError due to older version of python not contaning that exception
except OSError as e:
#Log the files that have not been moved to the console
logging.info(f'Files File already exists: {src_file}')
print(f'File already exists: {src_file}')
#os.remove to delete files that are already in dest repo
os.remove(src_file)
logging.warning(f'Deleting: {src_file}')
def file_loop(files, root):
for file in files:
#src_file is used to get the full path of everyfile
src_file = os.path.join(root,file)
#The two variables below are used to get the files creation date
t = os.stat(src_file)
c = t.st_ctime
#If the file is older then cutoff code within the if statement executes
if c<cutoff:
move_files(src_file)
#Log the file names that are not older then the cutoff and continue loop
else:
logging.info(f'File is not older than 14 days: {src_file}')
continue
def purge_files():
logging.info('invoke purge_files method')
#Walk through root directory and all subdirectories
for root, subdirs, files in os.walk(source):
dst_dir = root.replace(source, dest)
#Loop through files to grab every file
file_loop(files, root)
return files, root, subdirs
files, root, subdirs = purge_files()
I expected the output to move all files from source to dest. Before the files are moved I expected to check all files in the dest location including subdir of dest if any of them are the same file as the source then they wont be moved to the dest. I do not want the folders that are in source. I just want all the files to be moved to the root directory.