2015-03-25 92 views
1

我是一個新手,Python和從Python Tutorial的Python:打印文件的內容到終端

閱讀了有關文件,所以,我做了一個小程序,練習文件處理:

from sys import * 

script , file_name = argv 

print "Your file is : %s" %file_name 

print "Opening the file..." 
temp = open(file_name, 'r+') 

print "Truncating the file " 
temp.truncate() 

print "Enter three lines." 

line1 = raw_input("line 1: ") 
line2 = raw_input("line 2: ") 
line3 = raw_input("line 3: ") 

print "Writing these to the file." 

temp.write(line1) 
temp.write("\n") 
temp.write(line2) 
temp.write("\n") 
temp.write(line3) 
temp.write("\n") 


#for line in temp: 
     #print line 
#temp.read() 

print "Closing it." 
temp.close() 

我的問題:在共

不知怎的,我無法打印文件,使用任一註釋(#)的終端的內容陳述德以上。有人可以幫我嗎 ?

回答

2

您可以添加一行

temp.seek(0,0) 

for line in temp: 
    print line 
temp.read() 

因此重新設定指針文件的開頭。
有關seek()的更多信息,請參閱https://stackoverflow.com/a/11696554/1686094

+1

謝謝@Aaron,這非常有幫助:) – pranav 2015-03-25 03:29:23

3

當您追加到文件時,python正在讀取文件中「光標」位於最後的位置。

您需要關閉該文件並將其打開爲「r」,然後才能夠從頭開始對內容編制索引。