2014-05-08 107 views
0

我再一次的人學習學習Python在鍛鍊; Tibial 17艱難地系列和 之一,碰上了:打開文件,寫它,並打印出結果

out_file = open(to_file, 'w') 
out_file.write(indata) 

因此以下一些指令我把它轉換到形式:

with open(to_file, 'w') as out_file: 
    out_file.write(indata) 

不知道它是應該做的事情最好的辦法,但它奉命從文件讀取時使用。所以真的我的問題是我如何打印出我寫入out_file的內容。 我試圖簡單地用如下:

with open(to_file, 'rw+') as out_file: 
    out_file.write(indata) 
    print out_file.read() 

等幾個方面,但我不能得到它打印任何東西。只是想知道是否甚至可以這樣做,還是必須再次單獨打開文件才能打印出來。

而且包括其他的問題在這裏關於該主題的我如何使用打印與with

with open(to_file, 'r') as out_file: 
    print out_file.read() 

在此先感謝

+0

你爲什麼不只是印製印花呢?最後一個代碼片段的問題究竟是什麼? – jonrsharpe

+0

使用'r +'。 [教程在這裏。](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files) –

+0

寫入數據後,你可能在文件的末尾。所以沒有什麼可讀的:您需要將文件指針移回文件的開頭並從那裏讀取。 – Evert

回答

0

的問題,下面的代碼片段:

​​

是該文件的索引將在年底,因此,會有什麼閱讀。爲了解決這個問題,只需使用seek()

with open(to_file, 'r+') as out_file: 
    out_file.write(indata) 
    out_file.seek(0) 
    for line in out_file.readline(): 
    print line 

雖然,寫,在相同的代碼塊讀取變得毫無意義在現實生活中,你仍然應該有你寫的數據,因爲I/O對磁盤要比你使用,以保持數據的RAM更昂貴,所以你可能只是做:

with open(to_file, 'w') as out_file: 
    out_file.write(indata) 

with open(to_file, 'r') as in_file: 
    for line in in_file.readline(): 
    print(line) 
0

只是打印你所編寫的文件(我假設這是一個字符串) :

with open(to_file, 'rw+') as out_file: 
    out_file.write(indata) 
    print indata 

關於你的第二個問題,你可以閱讀和打印seperately行:

with open(to_file, 'r') as out_file: 
    for l in out_file.readlines() 
     print l 
0

你寫的文件後,你必須把它倒回至開始爲了讀你」 ve剛剛寫的:

In [152]: with open('test.file', 'w+') as out_file: 
    out_file.write(data) 
    out_file.seek(0) 
    print out_file.read() 
    .....:  
test string