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


当前回答

使用 os.path.exist 查看文件和目录:

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

使用 os.path.isfile 仅查看文件(注:以下是符号链接):

os.path.isfile(file_path)

其他回答

if os.path.isfile(path_to_file):
    try:
        open(path_to_file)
            pass
    except IOError as e:
        print "Unable to open file"

提取例外被认为是一个可接受的,和 Pythonic,方法的流量控制在您的程序. 考虑处理错误的文件与 IOErrors. 在这种情况下,一个 IOError 例外将被提取,如果文件存在,但用户没有阅读许可。

来源:使用Python:如何检查是否存在文件

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

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!')

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

如果您已经进口了NumPy用于其他用途,那么不需要进口其他图书馆,如Pathlib,OS,路径等。

import numpy as np
np.DataSource().exists("path/to/your/file")

这将根据它的存在返回真实或虚假。

使用 os.path.exists() 查看是否存在文件:

def fileAtLocation(filename,path):
    return os.path.exists(path + filename)
 

filename="dummy.txt"
path = "/home/ie/SachinSaga/scripts/subscription_unit_reader_file/"


if fileAtLocation(filename,path):
   print('file found at location..')
else:
   print('file not found at location..')

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