I am writing a script that does something to a text file (what it does is irrelevant for my question though). So before I do something to the file I want to check if the file exists. I can do this, no problem, but the issue is more that of aesthetics.
Here is my code, implementing the same thing in two different ways.
def modify_file(filename):
assert os.path.isfile(filename), 'file does NOT exist.'
Traceback (most recent call last):
File "clean_files.py", line 15, in <module>
print(clean_file('tes3t.txt'))
File "clean_files.py", line 8, in clean_file
assert os.path.isfile(filename), 'file does NOT exist.'
AssertionError: file does NOT exist.
or:
def modify_file(filename):
if not os.path.isfile(filename):
return 'file does NOT exist.'
file does NOT exist.
The first method produces an output that is mostly trivial, the only thing I care about is that the file does not exist.
The second method returns a string, it is simple.
My questions is: which method is better for letting the user know that the file does not exist? Using the assert
method seems somehow more pythonic.