[当我在浏览器中问这个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”进行编写。
尝试以下操作,使用os.path.exists
检查文件是否存在,如果存在,请使用os.remove
删除文件:
import os
if os.path.exists("Report.html"):
os.remove("Report.html")
with open("Report.html", "w") as f:
pass #do your thing