如何使用 Python 检查文件是否存在?
使用 Python 代码有两种方法可以检查计算机中是否存在某个文件。一种方法是使用 os.path 模块的 isfile() 函数。如果指定路径处存在文件,该函数将返回 true,否则返回 false。
>>> import os
>>> os.path.isfile("d:\Package1\package1\fibo.py")
True
>>> os.path.isfile("d:/Package1/package1/fibo.py")
True
>>> os.path.isfile("d:\nonexisting.txt")
请注意,要在路径中使用反斜杠,必须使用两个反斜杠来转义 Python 字符串。
另一种方法是当 open() 函数具有对应于不存在的文件的字符串参数时,会引发 IOError 异常。
try:
fo = open("d:\nonexisting.txt","r")
#process after opening file
pass
#
fo.close()
except IOError:
print ("File doesn't exist")
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP