+ 2
How to avoid data to vanished while reading a file in "Write mode"
How we can avoid the data to be vanished or lost while we open the file in "Write Mode" and also if unknowingly we lost the file content , so is there any way to retrieve it back?
6 Respuestas
+ 4
You mean: open a file in append mode?
open(file,'a')
instead of open(file,'w')...
Searching in documentation would answer you...
It's a good practice to read it to know what are the options of the functions/methods you are used ^^
+ 4
You can prevent overwriting a file unintentionally by checking first for its existence:
import os
if not os.path.exists(filename):
file = open(filename, 'w')
+ 2
As well as checking existence of file, you can make a backup copy of it before editing...
0
thanks visph, however if unknowingly opened file in w mode, then how can I safeguard my content of file before coming out of it.?
0
Thanks visph & FB
0
To put simply, you never ever use 'w' unless you mean to wipe the file clean if it exists. If you mean to read it you open it with 'r' if you mean to write to it you use 'a'.
'w' is good if you create a log of one single error and you timestamp the filename to ensure it stays unique.
Say you are debugging your code and you want to write down the output to a file and you name that file error03022017134251.txt which translates 03 February 2017 01:42pm and you throw those 51 seconds at the end just to make sure it is not overwritten by another error that occurs during the same minute.