When I try to write to a file that already exists, but the write fails, the file gets overwritten with nothing (i.e. it gets cleared - contents of the existing file are deleted).
Example:
alaa@vernal:~/Test$ echo "sometext" > testfile
alaa@vernal:~/Test$ cat testfile
sometext
In Python:
with open('testfile', 'w') as f:
f.write(doesntexist)
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'doesntexist' is not defined
The file is empty:
alaa@vernal:~/Test$ cat testfile
alaa@vernal:~/Test$
I tried to handle the exception like this but it still empties the file:
import traceback
with open('testfile', 'w') as f:
try:
f.write(doesntexist)
print('OK')
except:
print('NOT OK')
traceback.print_exc()
NOT OK
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
NameError: name 'doesntexist' is not defined
I tried handling it in a different way, but it still empties the file:
import traceback
try:
with open('testfile', 'w') as f:
f.write(doesntexist)
print('OK')
except:
print('NOT OK')
traceback.print_exc()
NOT OK
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
NameError: name 'doesntexist' is not defined
I feel like I'm missing something. Is there a straight forward way of handling this situation in Python to not clear the file if the write fails for any reason? Or do I have to resort to 'cleverer' code, for example: read the contents of the file first, and if the write fails, write it back again with the original contents, or maybe attempt to write the data to a temp file first, etc.?
doesntexistwhich holds the string to output, e.g.doesntexist=“text to write”or put quotes around doesntexist if you want that as the text to be output e.g.open(“myfile.txt”).write(“doesntexist”)testfilehassometextin it, but after the failed write in Python, the file was cleared. I wantsometextto still exist in it.f.write(['some', 'array'])the write will fail withTypeError: expected a string or other character buffer objectwhich is expected, but if the file I'm trying to write to existed and had content inside it, the contents of the file are cleared. My question is how can I avoid that?