

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- How do I check if a Python variable exists?
- Java Program to check whether a file exists or not
- How to check if a file exists or not using Python?
- How can I check whether a field exists or not in MongoDB?
- How do I copy a file in python?
- How do I check whether a checkbox is checked in jQuery?
- Check if a file exists in Java
- Check if a File exists in C#
- Check whether a value exists in JSON object?
- How to check if a file exists in Golang?
- Check whether given key already exists in a dictionary in Python
- How do I copy a binary file in Python?
- How do I check whether a field contains null value in MongoDB?
- How do I wrap a string in a file in Python?
- How do I check to see if a column name exists in a CachedRowSet in JDBC?
Advertisements