I am trying to create a function that moves the previous/old revisions of specific PDFs from a directory to the already created "Old PDF Drawings" directory. I have different PDFs numbers, they all end up in some revision, can be "Rev A", "Rev B", "Rev C", etc.
I want to keep in the current directory the last revision made, and moved the rest of each PDFs numbers to the "Old PDF Drawings" directory. In the case that there are not old revisions then, just leave the PDF in the current directory.
Will understand better when looking at the screenshot
I attached screenshot and code below:
def clean_folder():
# Old PDF Drawings
source_dir = folder_selected
target_dir = f'{folder_selected}/Old PDF Drawings'
print(source_dir)
print(target_dir)
file_names = os.listdir(source_dir)
for file_name in file_names:
if file_name: #NEED HELP HERE
shutil.move(os.path.join(source_dir, file_name), target_dir)
>Solution :
Sort the list in reverse order. Now, the newest for any prefix will be first. Then, as you process the list, if you haven’t seen the prefix before, leave it alone. If you HAVE seen the prefix before, move it.
def clean_folder():
# Old PDF Drawings
source_dir = folder_selected
target_dir = f'{folder_selected}/Old PDF Drawings'
print(source_dir)
print(target_dir)
file_names = os.listdir(source_dir)
file_name.sort(reversed=True)
prefixes = set()
for file_name in file_names:
prefix = file_name.split()[0]
if prefix not in prefixes:
prefixes.add(prefix)
else:
shutil.move(os.path.join(source_dir, file_name), target_dir)
