• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

3 Best Methods to Check if File or Directory Exist in Python

Aniruddha Chaudhari/54390/4
CodePython

Many times in program we need to handle reading and writing file. I am sure you might have come across when your program crashes if the file in the directory that you want to read does not exist.

And this happens for everyone if you start learning file handling in Python.

So the only solution to avoid a crash is using “Python check if file exists or not before performing any operations on file”.

In this tutorial, I am going to share you three different ways of checking file and directory existence before reading or writing it.

Using…

  • os Python module
  • Try block
  • pathlib Python module

If you are new to the file handling in Python, here is a code for reading the file in Python. (This code is written to read csv file format but it works for reading any type of files.)

Now let’s come to our topic…

How to write a code for Python check if file exists?

Here are three different methods you can use…

1.Using os Python module

The os module has method os.path.exists() to check the file existence in the directory.

Python Check if File Exist

import os
os.path.exists(test_file.txt)
#True

os.path.exists(no_exist_file.txt)
#False

Python Check if Directory Exist

import os
os.path.exists(test_dir)
#True

os.path.exists(no_exist_dir)
#False

There can be file and directory with the same name. If you check using above methods, you can not identify whether it is a file or a directory.

Suppose you want to check if file “test-data” is present or not. In case if there is a directory with the name “test-data”, above functionos.path.exists() will return True. This is not expected as you are interested in the file (not the directory).

To avoid this teeter, you can use the following method.

Code for Checking only Files:

import os
os.path.isfile("test-data")

Above method will return False if there is no file “test-data”, even if the directory present with the same name.

Even if the file is present, you can find whether the file is accessible to write or to execute.

How to check if the File is Accessible to read, write or execute?

You can check the file if it is accessible for the various mode of accessing the file (ex. read, write or execute) using method os.access().

Syntax:

os.access(<path>, <mode>)

Along with the file path, you can provide accessible mode:

  • os.F_OK: to check existence of the file path
  • os.R_OK: to check if file is accessible to read
  • os.W_OK: to check if file is accessible to write
  • os.X_OK:  to check if file is accessible to execute

This method returns True or False based on the existence of file path and permission to access the various accessible mode.

import os
if os.access("/file/path/foo.txt", os.F_OK):
	print "Given file path is exist."

if os.access("/file/path/foo.txt", os.R_OK):
	print "File is accessible to read"

if os.access("/file/path/foo.txt", os.W_OK):
	print "File is accessible to write"

if os.access("/file/path/foo.txt", os.X_OK):
	print "File is accessible to execute"

This is the very useful method if you want to check the file for particular access mode.

2. Using try Block:

You can open the file using method open(). It checks if the file is accessible or not in your program.

Syntax for Opening the File:

open(<file/path>)

If you open the file directly without checking its existence, the program may crash. As like general exception handling, you can use try block to catch the exception.

There can be many reasons if you are not able to access the file in your program.

  • If you are trying to open the file which is not present it will throw an exception as FileNotFoundError.
  • If the file is present but if you don’t have permission to access it in your program, it throws an error as PersmissionError.

So here is a code for Python check if file exists…

try:
	f =open()
	#Perform File Operations (Reading and Writing a File)
	f.close()
except FileNotFoundError:
	print "File is not found."
except PersmissionError:
	print "You don't have permission to access this file."

It is not necessary you have to handle all the exception individually. All these exceptions come under the parent exception IOError.

So you can simply write a program to handle all the file check exception as follows…

try:
	f =open()
	#Perform File Operations (Reading and Writing a File)
	f.close()
except IOError:
	print "File is not accessible."

Using try block for Python check if the file exists is very simple and graceful to handle all the exception.

Doing it more pythonic way (as per Vernon Cole explained in the comment)…

myfilename = ‘my_file.txt’
try:
	with open(myfilename) as myfile:
		for line in myfile:
			print(line.strip())
except IOError:
	print(‘Trouble using file {}’.format(myfilename))

And good thing is… you don’t need to import any external module for using it.

3. Using pathlib Python module

The module pathlib is available in Python 3. If you are using Python 2 version, you can install as 3rd party module.

First, you have to create path object by passing the path of the file. This path can be a file name or directory path.

Check if the Path is Exist or not:

path = pathlib.Path("path/file")
path
path.exist()

Check if the Path mentioned is a file or not:

path = pathlib.Path("path/file")
path
path.is_file()

This is all about this tutorial for Python check if file exists. If you have any doubt, feel free to write in the comment section. I will reply to your every query as soon as possible.

Other File Program you can give a try to explore File handling in Python:

  • Read CSV file | With Example
  • Find the longest line from file in Python Program

See you soon in next Python Tutorial!

Python Interview Questions eBook

Python
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Vernon Cole
    July 31, 2017 at 5:51 pm

    The second example would be more clear if it were explained that the file is actually processed in the “try” block — not just opened and closed to test for accessibility.
    This is more “Pythonic” — that is clearer to read and more efficient to execute — than testing for accessibility, then later opening the file. It also eliminates a possible window of time, between testing for the existence of the file and opening it for use, when an outside agent could remove the file.

    myfilename = 'my_file.txt'
    try:
        with open(myfilename) as myfile:
            for line in myfile:
                print(line.strip())
    except IOError:
        print('Trouble using file {}'.format(myfilename))<>/pre
    • Reply
      Aniruddha Chaudhari
      July 31, 2017 at 6:21 pm

      Hi Vernon,

      I was expecting for file processing in between file opening and closing it, though I missed commenting explicitly. Updated code by adding appropriate comment between open and close file.

      Your code seems more Pythonic and I have added code snippet in the post from your comment.

      Thanks Vernon for taking concern. I really appreciate.

      Happy Pythoning!

  • Reply
    Vernon Cole
    July 31, 2017 at 5:56 pm

    I see that code markup for comments to the blog are difficult. I will use dots to replace Python white space…

    myfilename = ‘my_file.txt’
    try:
    .. with open(myfilename) as myfile:
    …. for line in myfile:
    …… print(line.strip())
    except IOError:
    .. print(‘Trouble using file {}’.format(myfilename))

    • Reply
      Aniruddha Chaudhari
      July 31, 2017 at 6:25 pm

      Yeah, comment section lacks for code markup configuration. I have updated your first comment with proper Python markup standard and indentation.

      Thanks, Great to see you here!

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard