2

Here is some code.

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

The results I expect are

  1. If an old version of 'Report.html' exists, then remove it.
  2. Open a new 'Report.html' for writing.

When I search for this question I get lots of answers (to other questions). This is probably because the answer is very easy, but I just do not understand how to do it.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Elbert
  • 29
  • 1
  • 1
    Aren't you looking for `with open('somefile.txt', 'w+') as f:` ? Note the `w+`. – Jan Dec 29 '19 at 22:29
  • 2
    The `+` in `w+` is for updating (i.e. read and write); since the question is about writing, I don't think that's necessary. – Roel Schroeven Dec 29 '19 at 22:31
  • 2
    if you use `open( ..., "w")` then it will remove old content in file. – furas Dec 29 '19 at 22:37
  • 1
    How do you know it doesn't work? See how to create a [mcve]. – Peter Wood Dec 29 '19 at 22:37
  • can just use `w` here when opening, which is defined as `open for writing, truncating the file first`, so it will empty the file and write your new data. If the file didnt exist it would create it. – Chris Doyle Dec 29 '19 at 22:38
  • Beside the point, but [a bare `except` is bad practice](https://stackoverflow.com/q/54948548/4518341). You should at least change it to `except Exception`, but preferably a specific exception like `OSError`. – wjandrea Dec 29 '19 at 23:12
  • 1
    You should include in your question the results you ARE getting when you run your code, that you think are incorrect. However, @furas is correct that you can just open a file for write and it will erase the old file automatically (unless it's open by someone else.) – RufusVS Dec 29 '19 at 23:15

2 Answers2

1

There's no need to remove the file when you can just empty it. File mode w will "open for writing, truncating the file first", and if the file doesn't exist, it will create it.

sbfldr = input('Enter subfolder name: ')

fname = os.path.join(sbfldr, 'Report.html')
with open(fname, 'w') as fwrite:
    pass  # Actual code here

BTW this uses a with-statement, which is the best practice for opening files. As well it ignores the bad error handling (bare except) and unnecessary exit() in your program.

Thanks to @furas for mentioning this in the comments

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

Try the following, using os.path.exists to check if the file exists, and os.remove to remove it if so:

import os
if os.path.exists("Report.html"):
    os.remove("Report.html")

with open("Report.html", "w") as f:
    pass #do your thing
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76