Back to: Python Programming
0
Python can check to see if a file exists on the computer. The OS module provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The os and os.path modules include many functions to interact with the file system.
First – place a file on your PC in a location you remember called “pythonTest.txt”.
When specifying a path, either use \ or / – Python does not recognise \ unless preceded by
the \ escape character.
# \ is the escape sequence in a string so use \\
path = "c:\\data\\pythonTest.txt"
#alternatively use / in place of \ in the path
path = "c:/data/pythonTest.txt"
We can check that the path exists:
import os
path = "c:\\data\\pythonTest.txt"
if os.path.exists(path):
print("The specified path exists.")
else:
print("This location doesn't exist!")
We can check whether the path contains a directory or a file:
import os
path = "c:\\data\\pythonTest.txt"
if os.path.exists(path):
print("The specified path exists")
if os.path.isfile(path):
print("and it contains the file!")
elif os.path.isdir(path):
print("and it is a directory")
else:
print("This location doesn't exist!")
Outputs:
The specified path exists
and it contains the file!