Coding in Python 19 – More OS Module Fun

In video number 19 of the Coding in Python series, we continue working with the OS module.

YouTube player

Commands Used in this Video

Using the OS module to check if a file exists

#!/usr/bin/env python3


import os

file = "myfile.txt"
if os.path.isfile(file):
    print("The file exists.")
else:
    print("The file does not exist.")

Checking the existence of a user-designated file

#!/usr/bin/env python3


import os

file = input("Enter a file name: ")
if os.path.isfile(file):
    print("The file exists.")
else:
    print("The file does not exist.")

Checking for the existance of a file, and creating it if it does not exist

#!/usr/bin/env python3


import os

file = input("Enter a file name: ")

if os.path.isfile(file):
    print("The file exists.")
else:
    print("The file does not exist.")
    print("Creating it...")
    os.system('touch {}'.format(file))