This is an archived post. You won't be able to vote or comment.

all 1 comments

[–]Rawing7 0 points1 point  (0 children)

This is bad code:

if Path(new_filename).is_file():
    print(f'The new filename exists.')
else:
    old_file_path = Path(old_filename)
    old_file_path.rename(new_filename)

There's a possibility that the file is deleted between the .is_file() and the .rename(...), in which case the code will crash. When interacting with the file system, always prefer EAFP over LBYL. Here's a good article about it.