Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting file if it exists; python

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')
like image 230
Yui Avatar asked Apr 23 '13 11:04

Yui


3 Answers

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.

like image 147
Aya Avatar answered Sep 20 '22 19:09

Aya


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

like image 44
jamylak Avatar answered Sep 22 '22 19:09

jamylak


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.

like image 39
ndpu Avatar answered Sep 19 '22 19:09

ndpu