如何检查是否存在文件,而不使用试用声明?
当前回答
您可以使用 os.listdir 检查文件是否在特定目录中。
import os
if 'file.ext' in os.listdir('dirpath'):
#code
其他回答
如果您已经进口了NumPy用于其他用途,那么不需要进口其他图书馆,如Pathlib,OS,路径等。
import numpy as np
np.DataSource().exists("path/to/your/file")
这将根据它的存在返回真实或虚假。
使用 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
使用:
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.access):
尝试打开文件:打开文件将始终确认文件的存在. 你可以这样做一个函数: def File_Existence(filepath): f = open(filepath) return True 如果它是错误的,它将停止执行与未经处理的 IOError 或 OSError 在后续版本的 Python. 要捕获例外,你必须使用一个尝试,除了条款。
我还应该提到,有两种方式,你将无法验证一个文件的存在. 无论问题将被拒绝许可或没有这样的文件或目录. 如果你抓住一个IOError,设置IOError为e(如我的第一个选项),然后输入打印(e.args),以便你可以希望确定你的问题. 我希望它有助于! :)
如果文件是要打开的,您可以使用以下技术之一:
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!')
注意:此查找一个文件或指定的名称的目录。