Python r + read write read writes garbage to file

Can anyone explain why the following problem occurs. In Python 2.7.12, when reading, writing, and then reading again from a file, python seems to write garbage.

for example, when running this in python IDLE:

import os 
testPath = r"myTestFile.txt"

## Make sure the file exists and its empty
with open(testPath,"w") as tFile:
    tFile.write("")

print "Our Test File: ", os.path.abspath(testPath )

with open(testPath, "r+") as tFile:
    ## First we read the file 
    data = tFile.read()

    ## Now we write some data 
    tFile.write('Some Data')

    ## Now we read the file again
    tFile.read()

When the file is now viewed, the following data:

Some data @sb d Z ddlm Z ddd ยท YZ edkr ^ ddlm Z dddde ยท nd S (s9
Implement Idle Shell history mechanism with history

...

It seems to me that the read function starts to be read from the end of the file and into the memory of any object that comes after, but this is just pure speculation.

I looked at the text, which seems to be printed in a text file, and this data comes from:

Python27\Lib\idlelib\IdleHistory.py

, seek(0) , . , .

read(), , .

!

  • , Python 2.7.12 Python 3.5.2 python 3.5.2 .
+4

Source: https://habr.com/ru/post/1659582/


All Articles