100 days of code: Day 17 - files

Last modified on 2020-06-25

Source: 100-days-of-code.

Building on yesterday’s use of exceptions, I wrote a program - verify_file.py - that works with files: first, verifying that a filename has been specified using a command line argument; then, verifying that the file exists using os.path.isfile() and, if not, creating it using with open(filename, 'w+')

import sys
import os

try:
    filename = sys.argv[1]
except IndexError:
    print("\nError: File not specified.")
else:
    if os.path.isfile(filename):
        print("\nFile exists.")
    else:
        with open(filename, 'w+') as f:
            print(f"\nFile created.")

Run …

$ ./verify_file.py 

Error: File not specified.
$ ./verify_file.py foobar.txt

File created.
$ ./verify_file.py foobar.txt

File exists.

Happy hacking!