How do I check whether a file exists using Python? -
how check whether file exists, without using try
statement?
if reason you're checking can if file_exists: open_it()
, it's safer use try
around attempt open it. checking , opening risks file being deleted or moved or between when check , when try open it.
if you're not planning open file immediately, can use os.path.isfile
return
true
if path existing regular file. follows symbolic links, both islink() , isfile() can true same path.
import os.path os.path.isfile(fname)
if need sure it's file.
starting python 3.4, pathlib
module offers object-oriented approach (backported pathlib2
in python 2.7):
from pathlib import path my_file = path("/path/to/file") if my_file.is_file(): # file exists
to check directory, do:
if my_file.is_dir(): # directory exists
to check whether path
object exists independently of whether file or directory, use exists()
:
if my_file.exists(): # path exists
you can use resolve()
in try
block:
try: my_abs_path = my_file.resolve(): except filenotfounderror: # doesn't exist else: # exists
Comments
Post a Comment