Possible Duplicate:
Weird behavior when writing and reading file
When I try to write into a file and then read it, I get an unexpected result.
My code is:
f=open("z.txt","w+")
f.write("Hello")
content=f.read()
print content
f.close()
The outputted file is:
Hellolף ן (I11 (S’QUEUE’ p1 (S’exec’ p2 S’runcode’ p3
(cidlelib.rpc unpickle_code p4
(S’c\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00@\x00\x00\x00s6\x00\x00\x00e\x00\x00d\x00\x00d\x01\x00\x83\x02\x00Z\x01\x00e\x01\x00j\x02\x00d\x02\x00\x83\x01\x00\x01e\x01\x00j\x03\x00\x83\x00\x00Z\x04\x00e\x01\x00j\x05\x00\x83\x00\x00\x01d\x03\x00S(\x04\x00\x00\x00s\x05\x00\x00\x00z.txts\x02\x00\x00\x00w+t\x05\x00\x00\x00HelloN(\x06\x00\x00\x00t\x04\x00\x00\x00opent\x01\x00\x00\x00ft\x05\x00\x00\x00writet\x04\x00\x00\x00readt\x07\x00\x00\x00contentt\x05\x00\x00\x00close(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00s\x17\x00\x00\x00C:/Users/x/Desktop/zt\x08\x00\x00\x00\x01\x00\x00\x00s\x06\x00\x00\x00\x0f\x01\r\x01\x0c\x01′
tRp5 tp6 (dp7 ttp8 tp9 . ‘2ר ְ ז׀l Ak !
€qg ¸Ck PCk $ ְBkאBkנBk 8Ck
xCk XBkxBk °Ck׀CkנCkDk
@‘ (Ck˜Ck kצ Ck Ck
ְpg DkDֽ˜F ! €qg + ˜Ck
(Dk
@k @k xDk ר?k @f HDkhDkpDk ˜Dk
נDkEk0EkPEk ְ” kצ
ְpg ! ˜F ,
״Dk@k @k ר?k
What am I doing wrong?
I believe this is a Windows issue, to do with filesystem block sizes. If you
.flush()the.write()before you.read(), it will work fine. I can reproduce it on Win7.(I think what is happening is that Windows allocates your file in blocks of 4KB, so writing
"Hello"bumps you up to the next block size. If you then.read()you get random gibberish from the rest of the block, because Python hasn’t had a chance to deal with it yet. If you.flush()before.read()ing, Python writes out the file properly and then you just get an empty string.)