+ 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?

9th Jan 2017, 7:17 AM
Anuj Gupta
Anuj Gupta - avatar
6 Antworten
+ 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 ^^
9th Jan 2017, 9:08 AM
visph
visph - avatar
+ 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')
9th Jan 2017, 3:48 PM
Free Boro
Free Boro - avatar
+ 2
As well as checking existence of file, you can make a backup copy of it before editing...
9th Jan 2017, 7:26 PM
visph
visph - avatar
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.?
9th Jan 2017, 10:00 AM
Anuj Gupta
Anuj Gupta - avatar
0
Thanks visph & FB
10th Jan 2017, 3:11 AM
Anuj Gupta
Anuj Gupta - avatar
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.
3rd Feb 2017, 7:51 AM
Dawid Borusiak
Dawid Borusiak - avatar