英文:
Why can I only print the text of a text file once?
问题
我写了一个小类,它可以读取一个文本文件,并且有一个打印文本的方法(file.output())。第一次调用它正常工作,但第二次调用该方法时什么都没有发生。我不明白为什么,因为我假设 FOR 循环不会改变任何内容。
class Datei():
def __init__(self, filename):
self.fileobject = open(filename)
def output(self):
for line in self.fileobject:
print(line.rstrip())
def end(self):
self.fileobject.close()
file = Datei("yellow_snow.txt")
file.output()
print("second try")
file.output()
file.end()
我预期文本文件的文本会被打印两次,但实际只打印了一次。
英文:
I have written a little class which reads a text file and which have a method for printing the text (file.output()). For the first call it worked, but the second call of the method nothing is happening. I do not understand why, since I assume that the FOR-Loop does not change anything.
class Datei():
def __init__(self, filename):
self.fileobject = open(filename)
def output(self):
for line in self.fileobject:
print(line.rstrip())
def end(self):
self.fileobject.close()
file = Datei("yellow_snow.txt")
file.output()
print("second try")
file.output()
file.end()
I expected the text of the text file to be printed twice, but it is only printed once.
答案1
得分: 6
当您读取文件时,您会通过文件指针移动,现在它位于文件末尾 - 您可以使用.seek(0)
返回到开头(或其他位置,0
是您开始的地方,如果您不是在附加模式下,则是开头)
with open(path) as fh:
print(fh.tell()) # 文件开头
print(fh.read()) # 获取所有内容并显示
print(fh.tell()) # 文件末尾
fh.seek(0) # 返回到开头
print(fh.tell()) # 文件开头
print(fh.read())
更多详细信息请参阅Python文档 7.2.1. 文件对象的方法。
英文:
When you read a file, you move a pointer through it, and it's now at the end - you can .seek(0)
to get back to the start (or other positions, 0
is where you started from, which is the beginning if you're not in append mode)
with open(path) as fh:
print(fh.tell()) # start of file
print(fh.read()) # get everything and display it
print(fh.tell()) # end of file
fh.seek(0) # go back to the beginning
print(fh.tell()) # start of file
print(fh.read())
More detail in Python Documentation 7.2.1. Methods of File Objects
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论