Feb-14-2023, 02:03 PM
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
Please help.
Thanks.
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.