3 Ways to Check if File exists in Python

Most often while writing Python Code, you need to either write to a file or dead something from a file. For doing both of these operations(writing or reading) from a file firstly you need to create a file or need to check if file exists.
This testing of whether some file exists or not can be done in three ways –

  • Using open() Function
  • Using os.path Module
  • Using pathlib Module

Let’s see How each one of this method can be used for checking whether file exists or not?

Using open() Function

This is one of simplest approach for checking whether file exists or not. Here you need to use try…..except….finally code block and open() Function, try block will be used for test to open file and then throughing some error if file not exist.
Below is code for doing this.

try:
	f = open("filename.txt")
except FileNotFoundError:
	print("File not found")
finally:
	f.close()

This is quite simple method, just keeps in mind to do closing of file object f.close() cleanup. Moreover in order to do this cleanup automatically instead of using finally: with open() as f: can be used.
Below is code for this.

try:
	with open("filename.txt") as f:
		print(f.readlines())
except FileNotFoundError:
	print("File not found")

Using os.path module for Testing File Existence in Python

Python’s os.path module provides a number of functions specifically for dealing with file paths and directories in File System. Specifically for checking whether some file exists or not os.path.isfile(path) function can be used which returns True if path is a File otherwise return False.
Below is a code example showing How to use os.path.isfile() function?

import os.path

if os.path.isfile('somefile.txt'):
	print("Yes, File exists")
else:
	print("No, File does not exist")

Using Python’s pathlib Module for checking Existence of File

From pathlib module import Path and then use Path().is_file() function to check whether file exists or not. Path().is_file() returns True if file exists false otherwise.
Below is a code example showing this.

from pathlib import Path

if Path('somefile.txt').is_file():
	print("Yes, File does exists")
else:
	print("No, File does not exist")

You May Also Like

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts