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


当前回答

另一个可能的选项是检查文件名是否在目录中使用 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

使用:

import os

# For testing purposes the arguments defaulted to the current folder and file.
# returns True if file found
def file_exists(FOLDER_PATH='../', FILE_NAME=__file__):
    return os.path.isdir(FOLDER_PATH) \
        and os.path.isfile(os.path.join(FOLDER_PATH, FILE_NAME))

它基本上是一个文件夹检查,然后使用 os.path.join 使用适当的目录分离器进行文件检查。

使用 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..')

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

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

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

您可以使用以下开放方法检查是否存在 + 可阅读的文件:

file = open(inputFile, 'r')
file.close()