python - 如何删除然后打开一个文件以用 python 编写?
问题描述
这是一些代码。
sbfldr = input('Enter subfolder name: ')
try:
os.remove(os.path.join(sbfldr, 'Report.html'))
except:
print('Remove error. Please close the report file')
exit()
try:
fwrite = open(os.path.join(sbfldr, 'Report.html'),'a')
exit()
except:
print('Open error. Please close the report file')
exit()
我期望的结果是
- 如果存在旧版本的“Report.html”,则将其删除。
- 打开一个新的“Report.html”进行写作。
当我搜索这个问题时,我得到了很多答案(其他问题)。这可能是因为答案很简单,但我只是不明白该怎么做。
解决方案
当您可以清空文件时,无需删除文件。文件模式w
将“打开写入,先截断文件”,如果文件不存在,它将创建它。
sbfldr = input('Enter subfolder name: ')
fname = os.path.join(sbfldr, 'Report.html')
with open(fname, 'w') as fwrite:
pass # Actual code here
顺便说一句,这使用with
-statement,这是打开文件的最佳实践。它也忽略了程序中不必要的错误处理(bareexcept
)和不必要exit()
的。
推荐阅读
- tensorflow - 为什么 Keras 中的 plot_model 不能正确绘制模型?
- javascript - 当我单击单选按钮时,它不会立即刷新
- android - 如果 Android 项目不在根级别,App Center 将无法找到它
- python - 如何在 python 中使用 TKINTER 进行退格
- mysql - 违反完整性约束 - 1452 无法添加或更新子行
- python - Django:如何从其他模型中添加多对多值
- c - scanf() 和整数数组
- java - 如何找到连接选定顶点(顶点子集)的最小连接器
- python - 从 perl 调用 python - 方法调用不正确
- python - Django错误的用户名,自定义用户模型的密码