python - 在 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()
解决方案
请尝试运行以下代码。您尚未通过模式类型。如果发生任何异常,请在此处发表评论。
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")
推荐阅读
- java - java.lang.AbstractMethodError:org.apache.cxf.transport.http.asyncclient.AsyncHTTPConduitFactory.createConduit
- javascript - TypeError:无法读取 null 的属性“memberCount”
- python - 如何使函数检查字符串中有多少个辅音或元音?
- oracle - 如何增加 Oracle Reports 6i 中显示的行数?
- typescript - 防止 TypeScript 编译器退出批处理脚本
- linux - 如何在linux终端命令中使用#
- android - 使用 Jetpack 导航组件在一个屏幕上显示多个片段
- ios - 从 Native iOS 向 React Native 发送自定义数据类型
- excel - 按名称访问工作表,包括 ThisWorkbook
- javascript - 每次单击跨度时如何为 div 运行函数?