Jalaj
Jalaj

Reputation: 463

Opening file in 'r+' mode is giving weird output

I need to open a file for both reading and writing to a file. After reading some articles I fond that I can use the 'r+' mode. Here's what I want to achieve:

  1. Open the file and read data from it.
  2. Analyze and manipulate the data.
  3. Delete the contents of the file.
  4. Write new content to it.

But when I tried it, I got some weird outputs. Here are the screenshots:

First I tried this:

enter image description here

You'll notice that the data is appended(not what I wanted). So, I tried to truncate the file before writing to it:

enter image description here

Now, why am I getting those weird bytes at the start? Thanks.

PS I am on python 3.8.2 running on Windows 10.

Upvotes: 2

Views: 179

Answers (2)

lightBullet
lightBullet

Reputation: 113

In first scenario:
After you open and read the file, the position of the file handle changes to the end of the file. You can get the current position of the file handle using tell().

>>> f = open('test', 'r+')
>>> f.read()
'Read file\n'
>>> f.tell()
10
>>>

On your write operation, it writes to the end of the file (here, 10th position). That is the reason for your output.

In second scenario:
The same thing happens. You read the file and the file handle changes to the end of the file. After you truncate the file to 0, the file handle still remains at the earlier position.

>>> f = open('test', 'r+')
>>> f.read()
'Read file\n'
>>> f.tell()
10
>>> f.truncate(0)
0
>>> f.tell()
10
>>>

You start writing from this position and all the bytes before that is filled with null character. That is the reason for your second output.

Solution would be to seek() the file handle to 0 after truncating the file, and then start your write operation.

>>> f = open('test', 'r+')
>>> f.read()
'Read file\n'
>>> f.truncate(0)
>>> f.seek(0)
0
>>> f.write('New write')
9
>>> f.close()
>>> f2 = open('test', 'r+')
>>> f2.read()
'New write'

Also I would suggest you to take a look at this for better understanding of file objects.

Upvotes: 2

DirtyBit
DirtyBit

Reputation: 16772

using the different modes separately:

with open("dummy.txt", "r") as fileObj:
    print(fileObj.readlines())

with open("dummy.txt", "w") as fileObj:
    fileObj.write('New Content')

OUTPUT:

dummy.txt:

New Content

Upvotes: 1

Related Questions