【问题标题】:Python : Printing contents of a file to the terminalPython:将文件的内容打印到终端
【发布时间】:2015-03-25 11:25:21
【问题描述】:

我是 Python 的新手,正在阅读来自 Python Tutorial 的文件

所以,我做了一个小程序来练习文件处理:

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 file terminal


    【解决方案1】:

    当您附加到文件时,python 正在读取文件中“光标”所在的位置,即文件末尾。

    您需要关闭文件并以“r”打开它,然后您才能从头开始索引内容。

    【讨论】:

      【解决方案2】:

      你可以加一行

      temp.seek(0,0)
      

      之前

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

      因此再次将指针设置为文件的开头。
      有关seek() 的更多信息,请参阅https://stackoverflow.com/a/11696554/1686094

      【讨论】:

      • 谢谢@Aaron,这很有帮助:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-23
      • 2013-03-03
      • 1970-01-01
      • 2013-06-16
      • 2014-09-16
      • 1970-01-01
      • 2014-06-18
      相关资源
      最近更新 更多