在 PYCHARM 中使用 'try & except' 时出现问题。 'except'不是工作。它给了我'f is not definded'


try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()

请尝试运行下面的代码。您没有传递模式类型。如果出现任何异常,请在此处注释。

try:
f = open("demofile.txt", "w")
f.write("Lorum Ipsum")
except Exception as e:
print(e)
finally:
f.close()

你也可以在这里用with。因为这个方法会在文件操作完成后自动关闭打开的文件。

with open("demofile.txt", "w") as f:
f.write("Lorum Ipsum")

最新更新