gpt4 book ai didi

python - 如果一两个文件不存在,如何处理异常?

转载 作者:太空宇宙 更新时间:2023-11-03 21:36:26 25 4
gpt4 key购买 nike

我正在尝试检查是否存在一个或两个文件,如下所示:

def check_files_if_exist():
try:
f1 = open(file1)
f1.close()
f2 = open(file2)
f2.close()
except:
#how to pass exception if one or two files does not exist?

我的问题是,如果一个或两个文件不存在,如何传递异常?

最佳答案

您可以使用pathlib.Path直接检查文件是否存在。模块。它带有Python。

from pathlib import Path
p = Path('/path/to/file.txt')
if p.exists():
# open file...
with p.open('r') as file:
for line in file:
line = line.strip()
# Do something here...

关于python - 如果一两个文件不存在,如何处理异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53218894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com