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))

1 Answer 1

  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.
  • \$\begingroup\$ very useful advice, thank you \$\endgroup\$ Dec 30, 2020 at 16:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.