如何检查是否存在文件,而不使用试用声明?
当前回答
在2016年,最好的方式仍然是使用os.path.isfile:
>>> os.path.isfile('/path/to/some/file.txt')
在Python 3中,您可以使用Pathlib:
import pathlib
path = pathlib.Path('/path/to/some/file.txt')
if path.is_file():
...
其他回答
使用 os.path.exist 查看文件和目录:
import os.path
os.path.exists(file_path)
使用 os.path.isfile 仅查看文件(注:以下是符号链接):
os.path.isfile(file_path)
您可以使用以下开放方法检查是否存在 + 可阅读的文件:
file = open(inputFile, 'r')
file.close()
另一个可能的选项是检查文件名是否在目录中使用 os.listdir():
import os
if 'foo.txt' in os.listdir():
# Do things
如果是真相,如果是虚假,如果不是真相。
不同于 isfile(), exist() 将返回 True for Directory. 因此,根据您是否只需要平板文件或 Directory,您将使用 isfile() 或 exist()。 这里有一些简单的 REPL 输出:
>>> os.path.isfile("/etc/password.txt")
True
>>> os.path.isfile("/etc")
False
>>> os.path.isfile("/does/not/exist")
False
>>> os.path.exists("/etc/password.txt")
True
>>> os.path.exists("/etc")
True
>>> os.path.exists("/does/not/exist")
False
在2016年,最好的方式仍然是使用os.path.isfile:
>>> os.path.isfile('/path/to/some/file.txt')
在Python 3中,您可以使用Pathlib:
import pathlib
path = pathlib.Path('/path/to/some/file.txt')
if path.is_file():
...
推荐文章
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 在烧瓶中返回HTTP状态代码201
- 使用python创建一个简单的XML文件
- APT命令行界面式的yes/no输入?
- 如何打印出状态栏和百分比?
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试