
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Check If 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")
Advertisements