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')
1

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This is a potential race condition, check os.path.exists before removing it that is
Another program may be operating on the file and deletes it just after os.path.exists evaluates to True.
Oh yup it's fine now, I realized just after I wrote mine you could use 'w' but I had that before
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

Comments

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.

2 Comments

@Yui I don't understand you said you want to delete it if it exists... Please update your question with no strings attached
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
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')

Comments

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

4 Comments

potential race condition here as well
There's no race condition now but the path.isfile(PATH) has become effectively redundant
Thank you, I thought it would make the solution safer.In this case I think my solution will be exactly same as Aya.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.