Taking a file path from user input in Python

avatar

Borislav Hadzhiev

Last updated: Aug 26, 2022

banner

Photo from Unsplash

Taking a file path from user input in Python #

To take a file path from user input:

  1. Use the input() function to take the file path as input from the user.
  2. Use the os.path.exists() method to check if the specified path exists.
main.py
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')

take file path from user input

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.

The 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.

main.py
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')
The 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.

main.py
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')

user input file path raise error

If the provided path doesn't exist, the else block runs where we raise a FileNotFoundError exception.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.