[英]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.