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


当前回答

這是最簡單的方式來檢查是否存在檔案. 只是因為檔案在您檢查時存在並不保證它會在您需要開啟時存在。

import os
fname = "foo.txt"
if os.path.isfile(fname):
    print("file does exist at this time")
else:
    print("no such file exists at this time")

其他回答

使用 os.path.isfile(), os.path.isdir() 和 os.path.exists() 的文件和文件夹进行测试

假设“路径”是有效的路径,此表显示了每个函数为文件和文件夹返回的内容:

此分類上一篇

您还可以测试文件是否是一种特定类型的文件,使用 os.path.splitext() 获取扩展(如果您还不知道)

>>> import os
>>> path = "path to a word document"
>>> os.path.isfile(path)
True
>>> os.path.splitext(path)[1] == ".docx" # test if the extension is .docx
True

此外, os.access():

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()

是 R_OK, W_OK, 和 X_OK 旗帜测试许可证(doc)。

您可以使用 os.listdir 检查文件是否在特定目录中。

import os
if 'file.ext' in os.listdir('dirpath'):
    #code

它被认为是更好的风格,避免赛车条件。

不要用我的话来支持这个理论,这里有几个:

风格:本课程的“处理异常条件”部分为软件设计(2007) 避免竞赛条件

我是包的作者,已经在周围约10年,它有一个功能,直接解决这个问题. 基本上,如果你在一个非Windows系统,它使用Popen访问找到。

代码本身不使用试区块......除非确定操作系统,从而引导你到“Unix”风格的搜索或手建的搜索,时间测试表明,试图更快地确定操作系统,所以我使用其中一个(但没有其他地方)。

>>> import pox
>>> pox.find('*python*', type='file', root=pox.homedir(), recurse=False)
['/Users/mmckerns/.python']

而博士......

>>> print pox.find.__doc__
find(patterns[,root,recurse,type]); Get path to a file or directory

    patterns: name or partial name string of items to search for
    root: path string of top-level directory to search
    recurse: if True, recurse down from root directory
    type: item filter; one of {None, file, dir, link, socket, block, char}
    verbose: if True, be a little verbose about the search

    On some OS, recursion can be specified by recursion depth (an integer).
    patterns can be specified with basic pattern matching. Additionally,
    multiple patterns can be specified by splitting patterns with a ';'
    For example:
        >>> find('pox*', root='..')
        ['/Users/foo/pox/pox', '/Users/foo/pox/scripts/pox_launcher.py']

        >>> find('*shutils*;*init*')
        ['/Users/foo/pox/pox/shutils.py', '/Users/foo/pox/pox/__init__.py']

>>>

實施,如果你想看,在這裡: https://github.com/uqfoundation/pox/blob/89f90fb308f285ca7a62eabe2c38acb87e89dad9/pox/shutils.py#L190