如何检查是否存在文件,而不使用试用声明?


当前回答

TL;DR 答案是:使用 pathlib 模块


Pathlib 可能是几乎所有文件操作中最现代化和最方便的方式. 对于文件或文件夹的存在,一个单一的代码线就足够了. 如果文件不存在,它不会扔出任何例外。

from pathlib import Path

if Path("myfile.txt").exists(): # works for both file and folders
    # do your cool stuff...

pathlib 模块在 Python 3.4 中引入,所以你需要 Python 3.4+ 这个图书馆在使用文件和文件夹时使你的生活更容易,而且很方便使用。

BTW,如果你要重新使用路径,那么最好将其分配给一个变量。

因此,它将成为:

from pathlib import Path

p = Path("loc/of/myfile.txt")
if p.exists(): # works for both file and folders
    # do stuffs...
#reuse 'p' if needed.

其他回答

不同于 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

使用:

import os
#Your path here e.g. "C:\Program Files\text.txt"
#For access purposes: "C:\\Program Files\\text.txt"
if os.path.exists("C:\..."):
    print "File found!"
else:
    print "File not found!"

进口 OS 使您更容易与您的操作系统一起导航和执行标准操作。

请参见《如何检查没有例外的文件是否存在》。

如果您需要高级操作,请使用Shutil。

另一个可能的选项是检查文件名是否在目录中使用 os.listdir():

import os
if 'foo.txt' in os.listdir():
    # Do things

如果是真相,如果是虚假,如果不是真相。

如果文件是要打开的,您可以使用以下技术之一:

with open('somefile', 'xt') as f: # Using the x-flag, Python 3.3 and above
    f.write('Hello\n')

if not os.path.exists('somefile'): 
    with open('somefile', 'wt') as f:
        f.write("Hello\n")
else:
    print('File already exists!')

注意:此查找一个文件或指定的名称的目录。

虽然我总是建议使用尝试和除陈述,这里有几个选项为您(我的个人喜爱是使用os.access):

尝试打开文件:打开文件将始终确认文件的存在. 你可以这样做一个函数: def File_Existence(filepath): f = open(filepath) return True 如果它是错误的,它将停止执行与未经处理的 IOError 或 OSError 在后续版本的 Python. 要捕获例外,你必须使用一个尝试,除了条款。

我还应该提到,有两种方式,你将无法验证一个文件的存在. 无论问题将被拒绝许可或没有这样的文件或目录. 如果你抓住一个IOError,设置IOError为e(如我的第一个选项),然后输入打印(e.args),以便你可以希望确定你的问题. 我希望它有助于! :)