Python:将文件内容打印到终端

Python:将文件内容打印到终端,python,file,terminal,Python,File,Terminal,我是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 lin

我是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”的形式打开它,然后才能从一开始就为内容编制索引。

当您添加到该文件时,python将从文件中“光标”所在的位置(即文件末尾)读取内容

您需要关闭文件并以“r”的形式打开,然后才能从一开始就为内容编制索引。

您可以添加一行

temp.seek(0,0)
以前

for line in temp:
    print line
temp.read()
因此,再次设置指向文件开头的指针。
有关
seek()
的更多信息,请参见您可以添加一行

temp.seek(0,0)
以前

for line in temp:
    print line
temp.read()
因此,再次设置指向文件开头的指针。

有关
seek()
的更多信息,请参阅谢谢@Aaron,这非常有帮助:)谢谢@Aaron,这非常有帮助:)