python : Printing contents of a file to the terminal

标签 python file terminal

我是 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 将从文件中“光标”所在的位置读取,即末尾。

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

关于 python : Printing contents of a file to the terminal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29246745/

相关文章:

java - 从文件读取和写入任何数据结构?

python - 未使用 TensorFlow 编译的 CPU 指令

python - virtualenv 下的 getsitepackages 问题

python - 我无法解码打印以下 python 模式的逻辑。我应该对我的代码做哪些更改?

使用 NumPy 数据类型的 Python 字典查找速度

java - 循环遍历多个 YAML 文件以查找特定数据

perl - 第二次使用 open 时文件锁会保留吗?

shell - 为什么在使用 rmdir 时在终端中出现 "Directory not empty"错误?

Python 过滤器 defaultdict

python - 在 python 中通过按键调用函数的最简单方法(3)