Pythonic way to check if a file exists?
To check if a path is an existing file:
os.path.isfile(path)
Return
True
if path is an existing
regular file. This follows symbolic
links, so bothislink()
and
isfile()
can be true for the same
path.
How can I check if a file exists in python?
I think you just need that
try:
f = open('myfile.xlxs')
f.close()
except FileNotFoundError:
print('File does not exist')
If you want to check with if-else than go for this:
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists
How do I check if a file exists with * in python?
You should probably use glob rather than os functions here.
Glob also supports * characters, so it should do fine for your use case.
How do you check if a file exists or not?
You can use the os.path module to check if a file exists. The module is available for both Python 2 and 3.
import os.path
if os.path.isfile('filename.txt'):
print ("File exist")
else:
print ("File not exist")
Check to see if a file exists, and create it if it doesn't
You can use os.path.exists("schedule.dat")
. It returns a boolean result.
An alternative solution using os.stat
involves:
import os
try:
os.stat("schedule.dat")
... # file exists
except:
file = open("schedule.dat", "w")
...
An exception is raised is you try to stat
a non-existent file.
Related Topics
Syntaxerror Inconsistency in Python
Standard Way to Embed Version into Python Package
Where's My JSON Data in My Incoming Django Request
Python: Best Way to Add to Sys.Path Relative to the Current Running Script
How to Use Inspect to Get the Caller's Info from Callee in Python
Running Get_Dummies on Several Dataframe Columns
Python How to Write to a Binary File
Inverse Distance Weighted (Idw) Interpolation with Python
Selecting from Multi-Index Pandas
Splitting a Semicolon-Separated String to a Dictionary, in Python
Check If String Has Date, Any Format
How to Use Brew Installed Python as the Default Python
How to Access Pandas Groupby Dataframe by Key
Heapq with Custom Compare Predicate
Pandas Datetime to Unix Timestamp Seconds