18

I want to create a file; if it already exists I want to delete it and create it anew. I tried doing it like this but it throws a Win32 error. What am I doing wrong?

try:
    with open(os.path.expanduser('~') + '\Desktop\input.txt'):
        os.remove(os.path.expanduser('~') + '\Desktop\input.txt')
        f1 = open(os.path.expanduser('~') + '\Desktop\input.txt', 'a')
except IOError:
    f1 = open(os.path.expanduser('~') + '\Desktop\input.txt', 'a')
Yui
  • 181
  • 1
  • 1
  • 4
  • Does this answer your question? [Most pythonic way to delete a file which may not exist](https://stackoverflow.com/questions/10840533/most-pythonic-way-to-delete-a-file-which-may-not-exist) – crypdick Nov 22 '21 at 01:11

5 Answers5

41

You're trying to delete an open file, and the docs for os.remove() state...

On Windows, attempting to remove a file that is in use causes an exception to be raised

You could change the code to...

filename = os.path.expanduser('~') + '\Desktop\input.txt'
try:
    os.remove(filename)
except OSError:
    pass
f1 = open(filename, 'a')

...or you can replace all that with...

f1 = open(os.path.expanduser('~') + '\Desktop\input.txt', 'w')

...which will truncate the file to zero length before opening.

Aya
  • 39,884
  • 6
  • 55
  • 55
  • 2
    This is a potential race condition, check `os.path.exists` before removing it that is – jamylak Apr 23 '13 at 11:26
  • Another program may be operating on the file and deletes it just after `os.path.exists` evaluates to `True`. – jamylak Apr 23 '13 at 11:28
  • Oh yup it's fine now, I realized just after I wrote mine you could use `'w'` but I had that before – jamylak Apr 23 '13 at 11:32
  • 1
    safer way to do this: http://stackoverflow.com/questions/10840533/most-pythonic-way-to-delete-a-file-which-may-not-exist – mechatroner May 26 '15 at 01:17
3

You are trying to remove the file while it is open, you don't even need that with there to delete it:

path = os.path.join(os.path.expanduser('~'), 'Desktop/input.txt')
with open(path, 'w'): as f:
    # do stuff

Deletes if it exists

jamylak
  • 128,818
  • 30
  • 231
  • 230
2

You can use open with mode parameter = 'w'. If mode is omitted, it defaults to 'r'.

with open(os.path.expanduser('~') + '\Desktop\input.txt', 'w')

w Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.

ndpu
  • 22,225
  • 6
  • 54
  • 69
  • @Yui I don't understand you said you want to delete it if it exists... Please update your question with no strings attached – jamylak Apr 23 '13 at 11:33
  • Yes I want to delete it if it already exists before i start the script. After creating it anew I have multiple strings that get attached to the new file – Yui Apr 23 '13 at 11:36
1

Windows won't let you delete an open file (unless it's opened with unusual sharing options). You'll need to close it before deleting it:

try:
    with open(os.path.expanduser('~') + '\Desktop\input.txt') as existing_file:
        existing_file.close()
        os.remove(os.path.expanduser('~') + '\Desktop\input.txt')
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
1

Try this:

 from os import path, 
    PATH = os.path.expanduser('~') + '\Desktop\input.txt'
    if path.isfile(PATH):
       try:
          os.remove(os.path.expanduser('~') + '\Desktop\input.txt')
       except OSError:
          pass

edited :

from os import path, 
        PATH = os.path.expanduser('~') + '\Desktop\input.txt'
        try:
            os.remove(os.path.expanduser('~') + '\Desktop\input.txt')
        except OSError:
            pass
Maryam Arshi
  • 1,974
  • 1
  • 19
  • 33
  • potential race condition here as well – jamylak Apr 23 '13 at 11:53
  • There's no race condition now but the `path.isfile(PATH)` has become effectively redundant – jamylak Apr 23 '13 at 11:59
  • Thank you, I thought it would make the solution safer.In this case I think my solution will be exactly same as Aya. – Maryam Arshi Apr 23 '13 at 12:01
  • 1
    It doesn't make it any safer as Aya's. Your solution just does two checks instead of one, where the first one doesn't help the security at all, only the second does – jamylak Apr 23 '13 at 12:07