Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

How do I check whether a file exists without exceptions?

Solution:

In Python, you can check whether a file exists without causing exceptions using the os.path module or the pathlib module.

Let’s look at some examples.

If you are using os.path, here’s how to do it.


  import os

  file_path = "/path/to/your/file.txt"
  
  if os.path.exists(file_path):
       print(f"The file '{file_path}' exists. ")
  else:
       print(f"The file '{file_path}' does not exist. ")

However, if you are using pathlib:


  from pathlib import Path

file_path = Path("/path/to/your/file.txt")

if file_path.exists():
     print(f"The file '{file_path}' exists. ")
else: 
     print(f"The file '{file_path}' does notn exist. ")

Nevertheless, in both methods, you must use the exists() function, which returns True if the file or directory exists and False otherwise.

Want to know more about Python? Check out our blogs!