首页 > 解决方案 > 如何删除然后打开一个文件以用 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()

我期望的结果是

  1. 如果存在旧版本的“Report.html”,则将其删除。
  2. 打开一个新的“Report.html”进行写作。

当我搜索这个问题时,我得到了很多答案(其他问题)。这可能是因为答案很简单,但我只是不明白该怎么做。

标签: python

解决方案


当您可以清空文件时,无需删除文件。文件模式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()的。

感谢@furas在评论中提到这一点


推荐阅读