I’m learning python and have built a very simple program that just renames files. It makes all letters lowercase and replaces spaces and%20-instances with underscores and then copies them into a ‘Finished’ folder. I’m looking for better methods and approaches of writing and structuring my code.
Can anybody find any obvious imperfections or methods of improvement? If anyone has any advice then that would be great.
My code can be found below:
import osfrom shutil import copyfilefiles_to_improve_dir = 'Files to Improve'finished_files_dir = 'Finished'print('isdir', os.path.isdir(files_to_improve_dir))# 1 - copy files into 'finished' folderfor f in os.listdir(files_to_improve_dir): copyfile(os.path.join(files_to_improve_dir, f), os.path.join(finished_files_dir, f))for f in os.listdir(finished_files_dir): new_filename = f.replace(' ', '_').replace('%20', '_').lower() print('f', f, 'new_filename', new_filename) if (f != new_filename): os.rename(os.path.join(finished_files_dir, f), os.path.join(finished_files_dir, new_filename))1 Answer1
- Try using
pathliboveroswhen you're dealing with file/glob operations. It has a lot cleaner interface, and is part of standard library in python 3. - Name constants in your code with the
CAPITAL_SNAKE_CASE. It is recommended guideline fromthe PEP-8. - Split your code into individual functions doing a single task each.
- Put the execution flow for your code insidean
if __name__ == "__main__"block.
You mustlog in to answer this question.
Explore related questions
See similar questions with these tags.