I created a simple Python script to move files from a folder/directory to a newly created folder within the same path. The idea is to move files that were modified more than five days ago. I'm having issues where it is moving everything in the base path, including other subfolders. Is there a way to just move files, and not folders?
I tried the .endswith
function from the os.path
module, but no luck. I believe I am missing something revolving around a wildcard.
This is my code:
if not os.path.exists(new_path):
os.mkdir(new_path)
print('Successfully created the directory %s' % new_path)
else:
print('The directory %s already exists' % new_path)
for f in os.listdir(dir_path):
path_and_file = os.path.join(dir_path,f)
if int((datetime.datetime.fromtimestamp(os.path.getmtime(f)).strftime("%Y-%m-%d")).replace("-","")) < int(threshold_date.replace("-","")):
destpath_and_file = os.path.join(new_path, f)
shutil.move(path_and_file,destpath_and_file)
The code works, moving everything within the base folder. However, it is moving subfolders too. I would like to move files only. (For example, only move .xls/.xlsx files.)
Thank you very much.
Check that f is a file with os.path.isfile().
for f in os.listdir(dir_path):
if os.path.isfile(f):
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.