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 如何检查文件是否存在于 Python 中? 772 使用 Python,如何检查文件是否存在,而不使用try. 原始问题: spence91使用 Python检查文件是否存在 python 4 Answers Voted Best Answer César 2020-12-06T19:47:15+08:002020-12-06T19:47:15+08:00 您可以使用os.path.isfile: True如果路径是现有的常规文件,则返回。遵循符号链接,这样islink()并且isfile()对于同一路径可能是正确的。 import os.path os.path.isfile(fname) 如果您需要确定它是一个文件。 原答案: https://stackoverflow.com/a/82852/688393来自rslite 您可以使用@campussano 指示的方法os.path.exists(): import os.path as path if path.exists(file): # código 不同之isfile()处在于它将os.path.exists()返回True文件和文件夹 您可以使用@toledano 提供的方法,使用Python 中未包含的unipath模块,需要预先安装: $ pip install unipath 例子: from unipath import Path f = Path('ejemplo.txt') f.exists() 一般来说,使用unipath.PathI 发现它比 更简单os.path,尤其是在创建路由时。 # 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 我想你也可以使用: import os.path as path if (path.exists(file)): #todo:: toledano 2020-12-06T22:27:05+08:002020-12-06T22:27:05+08:00 该模块Unipath也有一个方法.exists()。 from unipath import Path f = Path('ejemplo.txt') f.exists() 一般来说,使用unipath.PathI 发现它比 更简单os.path,尤其是在创建路由时。 # 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 补充答案,这就是我验证文件存在于的方式Python: import os if os.path.isfile(archivo): isFile()返回true文件或目录。 os.path.isfile(path) true如果路径是现有文件,则返回。因此,这遵循符号链接,IsLink ()并且isfile ()对于相同的路径可能是正确的。
您可以使用
os.path.isfile
:如果您需要确定它是一个文件。
原答案:
您可以使用@campussano 指示的方法
os.path.exists()
:不同之
isfile()
处在于它将os.path.exists()
返回True
文件和文件夹您可以使用@toledano 提供的方法,使用Python 中未包含的unipath模块,需要预先安装:
例子:
一般来说,使用
unipath.Path
I 发现它比 更简单os.path
,尤其是在创建路由时。我想你也可以使用:
该模块
Unipath
也有一个方法.exists()
。一般来说,使用
unipath.Path
I 发现它比 更简单os.path
,尤其是在创建路由时。补充答案,这就是我验证文件存在于的方式
Python
:isFile()
返回true
文件或目录。