Last active
July 25, 2020 13:11
-
-
Save kurzweil777/c3e7ba1e66c808d8ac50c044008a4d5c to your computer and use it in GitHub Desktop.
Exercise from automate boring stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!python3 | |
import os | |
import re | |
"""Write a program that finds all files with a given prefix, such as spam001.txt , spam002.txt , | |
and so on, in a single folder and locates any gaps in the numbering (such as if there is a | |
spam001.txt and spam003.txt but no spam002.txt ). | |
Have the program rename all the later files to close this gap.""" | |
working_directory = str(input("Input your working directory with files: ")) | |
list_of_needed_numbers = [[correct_number + 1, number_of_file] for foldername, subfolder, filename in | |
os.walk(working_directory) for correct_number, number_of_file in enumerate(filename)] | |
regex = re.compile(r'''[0-9]{1,10}''') | |
def renaming(directory, needed_numbers): | |
for correct_number, current_filename in needed_numbers: | |
result = regex.findall(str(current_filename)) | |
number = str(correct_number) | |
try: | |
if ''.join(result) != number: | |
os.rename(os.path.join(directory, str(current_filename)), | |
os.path.join(directory, number + ".JPG")) | |
except FileExistsError: | |
continue | |
except FileNotFoundError: | |
continue | |
def check(directory, list_of_numbers): | |
for correct_number, current_filename in list_of_numbers: | |
if current_filename != f"{correct_number}.JPG": | |
renaming(directory, list_of_numbers) | |
else: | |
continue | |
if __name__ == "__main__": | |
check(working_directory, list_of_needed_numbers) | |
print("Job is done!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment