César Asked: 2020-12-06 19:47:15 +0800 CST 2020-12-06 19:47:15 +0800 CST 2020-12-06 19:47:15 +0800 CST How to check that a file exists in Python? 772 Using Python, how do I check if a file exists, without using the try. original question : Check whether a file exists using Python by spence91 python 4 Answers Voted Best Answer César 2020-12-06T19:47:15+08:002020-12-06T19:47:15+08:00 You can use os.path.isfile: Returns Trueif the path is an existing regular file. Follow symbolic links, such that islink()and isfile()can be true for the same path. import os.path os.path.isfile(fname) If you need to be sure it's a file. original answer: https://stackoverflow.com/a/82852/688393 from rslite You can use the method indicated by @campussano using os.path.exists(): import os.path as path if path.exists(file): # código The difference with isfile()is that it will os.path.exists()return Truefor files and folders You can use the method presented by @toledano using the unipath module which is not included in Python and needs to be installed previously: $ pip install unipath Example: from unipath import Path f = Path('ejemplo.txt') f.exists() In general, the use of unipath.PathI find it simpler than os.path, especially when creating routes. # con os.path os.path.join(A, B) # con unipath.Path Path(A, B) campussano 2020-12-06T22:21:27+08:002020-12-06T22:21:27+08:00 I think you can also use: import os.path as path if (path.exists(file)): #todo:: toledano 2020-12-06T22:27:05+08:002020-12-06T22:27:05+08:00 The module Unipathalso has a method .exists(). from unipath import Path f = Path('ejemplo.txt') f.exists() In general, the use of unipath.PathI find it simpler than os.path, especially when creating routes. # con os.path os.path.join(A, B) # con unipath.Path Path(A, B) Jorgesys 2020-12-07T11:48:40+08:002020-12-07T11:48:40+08:00 Complementing the answers, this is how I verify a file exists in Python: import os if os.path.isfile(archivo): isFile()returns truewith files or directories. os.path.isfile(path) Returns trueif the path is an existing file. This follows symbolic links, therefore, IsLink ()and isfile ()can be true for the same path.
You can use
os.path.isfile
:If you need to be sure it's a file.
original answer:
You can use the method indicated by @campussano using
os.path.exists()
:The difference with
isfile()
is that it willos.path.exists()
returnTrue
for files and foldersYou can use the method presented by @toledano using the unipath module which is not included in Python and needs to be installed previously:
Example:
In general, the use of
unipath.Path
I find it simpler thanos.path
, especially when creating routes.I think you can also use:
The module
Unipath
also has a method.exists()
.In general, the use of
unipath.Path
I find it simpler thanos.path
, especially when creating routes.Complementing the answers, this is how I verify a file exists in
Python
:isFile()
returnstrue
with files or directories.