How to Delete a File if It Exists in Python

file-iopythontry-catch

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

Best Answer

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.

Related Question