Pythonic Way to Check If a File Exists

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 both islink() 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



Leave a reply



Submit