Confusion with python file handling modes(The web is kinda confusing me, some clarification is needed) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Confusion with python file handling modes(The web is kinda confusing me, some clarification is needed)

1) For the mode 'w+', web says its supposed to write/read while it also overwrites(?) and I found out it can write but it also deletes pervious stuff so can't actually read using this. 2) mode 'a+' is also supposed to both read and write. When tried it out, it did write stuff without overwriting but prin(myfile.read()) just gives a blank and doesn't read. 3) So my conclusion is, ONLY 'r' and 'r+' can actually READ stuff from file? Please correct me wherever I'm wrong

21st Sep 2021, 5:52 PM
partha das
partha das - avatar
3 Answers
+ 2
partha das yes! But instead of believing me, you can try it yourself and it would help you understand all these operations in a better way. Also what i wrote might not be exactly how it works but generally that is what is happening (always do your research though).
21st Sep 2021, 6:23 PM
Abhay
Abhay - avatar
+ 3
"+" allows for reading but in first two when you write something the file pointer is moved to the last character in file. Since fp is at the end, reading the file doesn't do anything . You need to move fp to starting position and any other position where you want to read from . you can move the fp using seek . fp.seek(0) or fp.seek(8) , then you can use read or readline method to start reading from 0th or 8th character ! ps:fp=>file pointer. you can think of the above operation in terms of how hard drive works . To write something the actuator arm needs to move across the tracks and do something to write data to it . Now since the arm is at the last position there is no way you can read the characters you wrote and you will need to move that arm back to some other position and then it will do some operations to read those characters.
21st Sep 2021, 6:05 PM
Abhay
Abhay - avatar
+ 1
tyvm @abhay! if I understood correctly, w+ would overwrite and if fp seek is used it would read the new stuff only ? but a+ would append stuff at the end and if fp seek is used, can read previous data too ?
21st Sep 2021, 6:13 PM
partha das
partha das - avatar