2014-03-26 81 views
1

當我嘗試在Python中同時讀取和寫入.txt文件時,結果非常奇怪。Python,當讀取+同時寫入文件時出現奇怪的文字

from sys import argv 

script, filename = argv 

print """The contents of this .txt file will now be erased. 
if you don don't wish to do this. Hit CTRL+C. 
if you want to do this. Just click ENTER. 
""" 
raw_input("> ") 

target = open(filename, 'w+') #opens the file to read+write simultaneously 

newline1 = raw_input("the first line: ") #three lines of strings to add to the .txt file 
newline2 = raw_input("the second line: ") 
newline3 = raw_input("the third line: ") 


target.write(("%s\n%s\n%s") % (newline1, newline2, newline3)) #writes the lines to the file 

print "this is what's currently written inside the .txt file:\n" 
print target.read() #reads the contents of the file 
target.close() #closes and saves the file 

但隨後的文件只是讀出該jibberish(包括.txt文件裏面,當它在程序的讀取)的內容,而不是簡單的3線:

s· d Z d d l Z d e j f d „ ƒ YZ d e j f d „ ƒ YZ d e j f d „ ƒ YZ d e e j f d 
„ ƒ YZ d e e j f d „ ƒ YZ d 
„ Z d Z e j e ƒ Z 
d S( sv Python Character Mapping Codec cp1252 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT' with gencodec.py. 

iÿÿÿÿNt Codecc   B s e Z d d „ Z d d „ Z RS( t strictc   C s t j | | t ƒ S( N( t codecst charmap_encodet encoding_table( t selft inputt errors( ( s# C:\Python27\lib\encodings\cp1252.pyt encode s c   C s t j | | t ƒ S( N( R t charmap_decodet decoding_table( R R R ( ( s# C:\Python27\lib\encodings\cp1252.pyt decode s ( t __name__t 
    __module__R R ( ( ( s# C:\Python27\lib\encodings\cp1252.pyR   s t IncrementalEncoderc   B s e Z e d „ Z RS( c   C s t j | | j t ƒ d S( Ni ( R R R R ( R R t final( ( s# C:\Python27\lib\encodings\cp1252.pyR  s ( R R 
    t FalseR ( ( ( s# C:\Python27\lib\encodings\cp1252.pyR  s t IncrementalDecoderc   B s e Z e d „ Z RS( c   C s t j | | j t ƒ d S( Ni ( R R  R R 
    ( R R R ( ( s# C:\Python27\lib\encodings\cp1252.pyR  s ( R R 
    R R ( ( ( s# C:\Python27\lib\encodings\cp1252.pyR  s t StreamWriterc   B s e Z RS( ( R R 
    ( ( ( s# C:\Python27\lib\encodings\cp1252.pyR  s t StreamReaderc   B s e Z RS( ( R R 
    ( ( ( s# C:\Python27\lib\encodings\cp1252.pyR  s c   C [email protected] t j d d d t ƒ j d t ƒ j d t d t d t d t ƒ S(  Nt namet cp1252R R t incrementalencodert incrementaldecodert streamreadert streamwriter( R t  CodecInfoR R R R R R R ( ( ( s# C:\Python27\lib\encodings\cp1252.pyt getregentry! s  u–  

!"#$%&'()*+,-./:;<=>[email protected][\]^_`abcdefghijklmnopqrstuvwxyz{|}~€￾‚ƒ„…†‡ˆ‰Š‹Œ￾Ž￾￾‘’“â€â€¢â€「â€」˜™š›Å「￾žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÃÂÃÄÅÆÇÈÉÊËÌÃÃŽÃÃÑÒÃ「Ã」ÕÖ×ØÙÚÛÜÃÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ( t __doc__R R R R R R R R 
    t 
    charmap_buildR ( ( ( s# C:\Python27\lib\encodings\cp1252.pyt <module> s  ÿ   ó:›› ™øÌ pò  åP§ü      a^v– Qý LýHVzàý0DýI.*Èý ýJ²ã¨@ÏüðÒüK6=XÙü0Ùü      NÆü­ü ËüOžç5˜¯üp¯ü±v%P¿õýüQöy€Íüà­ü•ë[email protected]ýMýSž@3 èü˜õü_å’Ï`FýøDý   ßEïÐþü­ü¹ý¥t€ìüXþüXžf9`âü0Ùü   Z2ðÀãüˆÛü   O°s÷ÀýhØü]B] ìüþü^ÒÏZ€ýðý_NÅô Èü §ü   GbP€åüÐÞüDÆí OüXþü[email protected]ýxGýH¯«ÐPBý ¬üeú¿ýüðüüf¾Àëü(üüeõ5¸óüóü   ¼å»úXDý0Dý   k®à áüÔülš¦ âü0¤ü   n"éÍ@!ý8Aý½-ò¡àý¸ý   q.&yxLýPLý   s¦v8(×ü0Ôü   ¾]ª[àÝü¸Ýü; 
RE`ý ¬ü               |I\ ýÐ ýBÃœ」`ýÀý   0õ Èü°¦ü   fPãÑü@Íü‚ª¥¨¾õpðüƒª¥à¼õ0¤üMÕ—pJýHJý…JÃ1 ÍüpÐü   ‡ÊÑÈ@îüè ýˆd, Ïü`Ñü      ‹úDâ ý€ýŒêGœ€ýÀ@ýjhü ×üÔü½L ÀHýhHý   Æ Q`öü8öü\¤è½õ`Ñüõ\} ý°Aý      n¸ì™Àý° ý      ˜ª¥ð¾õÀúü™ª¥Ø¾õ¨ùüŽÞõ`ý¨Iý›¦[ ý€DýœÂ© Nü¸Ýü†T !ýÈBýžª¥À¾õñü    V$¶àìüøþü¡„½@ïüðý   £ŒMÀæüˆñü¤2/,ØühØüÆK¬§ ý€ý¦†? ýðý   ¨Šrxý° ý©†L 
`Ûü8Ûü   «þa 

編輯:在閱讀之前我添加了target.seek(0)行後,它工作。但是要知道是什麼原因導致亂語被寫出來仍然很有趣!

+0

在閱讀之前試試target.seek(0)? – Broseph

+0

如果不倒帶文件位置標題,則無法寫入,然後讀取。使用'file.seek()'來做('file.seek(0)'回到開始)。 –

+0

在print target.read()之前添加'target.seek(0)'給我預期的輸出。即使沒有'seek'調用,我仍然可以在文本文件中看到正確的輸出,我不知道你是如何在文件中得到太多亂碼的。 – GWW

回答

0

您可能想在嘗試之前嘗試file.flush()

否則,保持兩個手柄到文件:

file = open(filename, "w") 
file.write(stuff) 
file.close() 

file = open(filename, "r") 
file.read() 

我不認爲這是很好的做法,編寫和轉身再次讀取該文件。

相關問題