Last updated: Apr 9, 2024
Reading time·3 min
To take a file path from user input:
input()
function to take the file path as input from the user.os.path.exists()
method to check if the specified path exists.import os file_path = input('Enter a file path: ') # e.g. C:\Users\Bob\Desktop\example.txt # or /home/Bob/Desktop/example.txt print(file_path) if os.path.exists(file_path): print('The file exists') with open(file_path, 'r', encoding='utf-8-sig') as f: lines = f.readlines() print(lines) else: print('The specified file does NOT exist')
We used the input()
function to take a file path from user input.
The input function takes an optional prompt
argument and writes it to standard output without a trailing newline.
The next step is to use the os.path.exists() method to check if the file or directory exists.
os.path.exists()
method returns True
if the provided path exists and False
otherwise.The path may look something like: C:\Users\Bob\Desktop\example.txt
(Windows)
or /home/Bob/Desktop/example.txt
(Linux and MacOS).
You can use the with statement to open the specified file if it exists.
import os file_path = input('Enter a file path: ') # e.g. C:\Users\Bob\Desktop\example.txt # or /home/Bob/Desktop/example.txt print(file_path) if os.path.exists(file_path): print('The file exists') with open(file_path, 'r', encoding='utf-8-sig') as f: lines = f.readlines() print(lines) else: print('The specified file does NOT exist.')
with open()
syntax takes care of automatically closing the file even if an exception is raised.If the provided path doesn't exist, the else
statement runs and we print a
message to the user.
You can handle this any other way that suits your use case, e.g. by raising an error.
import os file_path = input('Enter a file path: ') # e.g. C:\Users\Bob\Desktop\example.txt # or /home/Bob/Desktop/example.txt print(file_path) if os.path.exists(file_path): print('The file exists') with open(file_path, 'r', encoding='utf-8-sig') as f: lines = f.readlines() print(lines) else: raise FileNotFoundError('No such file or directory.')
If the provided path doesn't exist, the else
block runs where we raise a
FileNotFoundError
exception.
You can learn more about the related topics by checking out the following tutorials:
__main__
module in Path