Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
r+ mode in files
#1
Hi Viewer,

I know r+ mode is used for reading and writing to a file. What I find strange is as soon as I open the file and then write to the file instead of reading, it writes from the first position. If I read first and then write to the file, it writes at the end of the file. Please see the code below:

test.data (created the file before running the code):

Welcome to Python line 1
Welcome to Python line 2
Welcome to Python line 3
Welcome to Python line 4

with open(file = 'test.data', mode = 'r+', encoding = 'utf-8') as fp:
    fp.write('new line\n')
The file gets modified as follows,

Output:
new line Python 1 Welcome to Python 2 Welcome to Python 3 Welcome to Python 4
Now I re-create the original text file test.data. And now when I read just first line and then write to it, it writes to the end of the file.

with open(file = 'test.data', mode = 'r+', encoding = 'utf-8') as fp:
    print(fp.readline())
    fp.write('new line\n')
    print(fp.readline())
The text file after the program executes:

Output:
Welcome to Python 1 Welcome to Python 2 Welcome to Python 3 Welcome to Python 4 new line
The following is the output from the above line of code:

Output:
Welcome to Python 1
I am unable to understand why Python does write to the file at the end of the file instead of at the location of the file pointer.

Please help.

Thanks.
Reply


Messages In This Thread
r+ mode in files - by grkiran2011 - Feb-14-2023, 02:03 PM
RE: r+ mode in files - by rob101 - Feb-14-2023, 03:24 PM
RE: r+ mode in files - by grkiran2011 - Feb-15-2023, 11:54 PM
RE: r+ mode in files - by deanhystad - Feb-14-2023, 09:03 PM
RE: r+ mode in files - by grkiran2011 - Feb-15-2023, 11:56 PM
RE: r+ mode in files - by DeaD_EyE - Feb-16-2023, 02:05 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  things that work in terminal mode but not in sublime mode alok 4 2,933 Aug-11-2021, 07:02 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020