Could anyone explain why the following problem occurs. In Python 2.7.12 when reading, writing and subsequently 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 now looking at the file the data is the following:
Some Data @ sb d Z d d l m Z d d d ・ ・ YZ e d k r^ d d l m Z e d d d d e ・n d S( s9
Implement Idle Shell history mechanism with History...
What it seems like to me is that the read function starts to read from the end of the file and into the memory of whatever object comes after but this is just pure speculation.
I looked up the text that seems to be printed into the text file and this data comes from:
Python27\Lib\idlelib\IdleHistory.py
Now I know i should use a seek(0)
after the write function to resolve the problem. But I am interested in why this problem occurs.
Why does the last read() call seem to write data to the file.
Thanks!
- note i tested it in Python 2.7.12 and Python 3.5.2 in python 3.5.2 it seems fixed and it does not write any garbage data.