- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I check whether a file exists using Python?
Presence of a certain file in the computer can be verified by two ways using Python code. One way is using isfile() function of os.path module. The function returns true if file at specified path exists, otherwise it returns false.
>>> import os >>> os.path.isfile("d:\Package1\package1\fibo.py") True >>> os.path.isfile("d:/Package1/package1/fibo.py") True >>> os.path.isfile("d:\nonexisting.txt")
Note that to use backslash in path, two backslashes have to be used to escape out of Python string.
Other way is to catch IOError exception that is raised when open() function has string argument corresponding to non-existing file.
try: fo = open("d:\nonexisting.txt","r") #process after opening file pass # fo.close() except IOError: print ("File doesn't exist")
- Related Articles
- How do I check if a Python variable exists?
- How to check if a file exists or not using Python?
- Java Program to check whether a file exists or not
- How can I check whether a field exists or not in MongoDB?
- How to check if a file exists in Golang?
- How do I copy a file in python?
- How do I delete a file in Python?
- Check if a File exists in C#
- Check if a file exists in Java
- Check whether given key already exists in a dictionary in Python
- How do I check whether a checkbox is checked in jQuery?
- How do I copy a binary file in Python?
- How do I create a .pyc file in Python?
- Check whether a value exists in JSON object?
- How do I check whether a field contains null value in MongoDB?

Advertisements