首页 > 解决方案 > 在 PYCHARM 中使用 'try & except' 时出现问题。'除了' 不是工作。它给了我'f is not defined'

问题描述

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

标签: pythontry-catchexcept

解决方案


请尝试运行以下代码。您尚未通过模式类型。如果发生任何异常,请在此处发表评论。

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")

推荐阅读