Skip to content

Latest commit

 

History

History
31 lines (17 loc) · 836 Bytes

201.md

File metadata and controls

31 lines (17 loc) · 836 Bytes

#如何使用Python来检查文件是否存在?

原问题地址:http://stackoverflow.com/questions/82831/how-to-check-whether-a-file-exists-using-python

##问题:

我如何使用Python而不使用try-catch语句来检查文件是否存在?

##答案 1

你也可以使用os.path.isfile

如果是一个现有的常规文件,就返回到True。这是符号链接,所以islink()isfile()可以适用于相同的路径。

import os.path
os.path.isfile(fname) 

如果你需要确保它是一个文件。

##答案 2:

os.path.exists

import os.path
os.path.exists(file_path)

如果是文件和目录,都会返回到True。但是你还可以使用os.path.isfile来专门查看它是否是一个文件。


打赏帐号:qiwsir@126.com(支付宝),qiwsir(微信号)