簡體   English   中英

Python:將文件內容打印到終端

[英]Python : Printing contents of a file to the terminal

我是Python的新手,正在從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()

我的問題:

不知何故,我無法使用以上代碼中的任何一個注釋(#)語句將文件的內容打印到終端。 有人可以幫我嗎 ?

當您追加到文件時,python將從文件中的“光標”位置開始讀取,即最后。

您需要關閉文件並將其打開為“ r”,然后就可以從頭開始索引內容。

您可以添加一行

temp.seek(0,0)

之前

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

因此,再次將指針設置到文件的開頭。
有關seek()更多信息,請參見https://stackoverflow.com/a/11696554/1686094

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM