3
\$\begingroup\$

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 os
from shutil import copyfile
files_to_improve_dir = 'Files to Improve'
finished_files_dir = 'Finished'
print('isdir', os.path.isdir(files_to_improve_dir))
# 1 - copy files into 'finished' folder
for 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))
hjpotter92
8,9011 gold badge26 silver badges49 bronze badges
asked Dec 29, 2020 at 20:04
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$
  1. Try using pathlib over os when you're dealing with file/glob operations. It has a lot cleaner interface, and is part of standard library in python 3.
  2. Name constants in your code with the CAPITAL_SNAKE_CASE. It is recommended guideline from the PEP-8.
  3. Split your code into individual functions doing a single task each.
  4. Put the execution flow for your code inside an if __name__ == "__main__" block.
answered Dec 29, 2020 at 20:51
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.