This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: File modes with '+' character does not give expected output
Type: behavior Stage: resolved
Components: Windows Versions: Python 3.8, Python 3.7, Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: anmolkejriwal, paul.moore, steve.dower, steven.daprano, tim.golden, zach.ware
Priority: normal Keywords:

Created on 2019-11-28 07:17 by anmolkejriwal, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg357609 - (view) Author: Anmol Kejriwal (anmolkejriwal) Date: 2019-11-28 07:17
The file modes a+, r+, w+ should read and write both. But a+ and w+ modes are not reading anything from the file. The RUN for the program is successful, but there is no output from the program.
Below is a simple program:

file=open("abcd.txt","w+")
l=["This is python.\nThis is an easy language.\nAnyone can learn this easily"]
file.writelines(l)
file.close()
file=open("abcd.txt","a+")   #Replacing with w+ also doesn't read.
file.write("123")      
t1=file.read()               #This read() does not work.
print(t1)                    #Does not print anything here.
file.close()

In r+ mode, it should write in the file without truncation and read it too. Instead, it is removing from the file, the equal number of characters I am trying to write in the file.
Below is the program:

file=open("abcd.txt","w+")
l=["This is python.\nThis is an easy language.\nAnyone can learn this easily"]
file.writelines(l)
file.close()
file=open("abcd.txt","r+")
file.write("123")
t1=file.read()
print(t1)

Output for this is:

s is python.
This is an easy language.
Anyone can learn this easily
msg357610 - (view) Author: Anmol Kejriwal (anmolkejriwal) Date: 2019-11-28 07:20
According to the doc,
https://docs.python.org/3/library/functions.html#open

The expected output for r+ mode in the program mentioned earlier should be:

123This is python.
This is an easy language.
Anyone can learn this easily
msg357611 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2019-11-28 07:29
This is expected behaviour. You read from the position of the file pointer, not the beginning of the file, so after writing to to the file, you have to use the seek() method to return to the beginning if you want to read what you just wrote.

https://docs.python.org/3/library/io.html

https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects
History
Date User Action Args
2022-04-11 14:59:23adminsetgithub: 83116
2019-11-28 07:29:19steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg357611

resolution: not a bug
stage: resolved
2019-11-28 07:20:26anmolkejriwalsetmessages: + msg357610
2019-11-28 07:17:15anmolkejriwalcreate