为什么我只能打印文本文件的文本一次?

huangapple go评论144阅读模式
英文:

Why can I only print the text of a text file once?

问题

我写了一个小类,它可以读取一个文本文件,并且有一个打印文本的方法(file.output())。第一次调用它正常工作,但第二次调用该方法时什么都没有发生。我不明白为什么,因为我假设 FOR 循环不会改变任何内容。

  1. class Datei():
  2. def __init__(self, filename):
  3. self.fileobject = open(filename)
  4. def output(self):
  5. for line in self.fileobject:
  6. print(line.rstrip())
  7. def end(self):
  8. self.fileobject.close()
  9. file = Datei("yellow_snow.txt")
  10. file.output()
  11. print("second try")
  12. file.output()
  13. 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.

  1. class Datei():
  2. def __init__(self, filename):
  3. self.fileobject = open(filename)
  4. def output(self):
  5. for line in self.fileobject:
  6. print(line.rstrip())
  7. def end(self):
  8. self.fileobject.close()
  9. file = Datei("yellow_snow.txt")
  10. file.output()
  11. print("second try")
  12. file.output()
  13. 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是您开始的地方,如果您不是在附加模式下,则是开头)

  1. with open(path) as fh:
  2. print(fh.tell()) # 文件开头
  3. print(fh.read()) # 获取所有内容并显示
  4. print(fh.tell()) # 文件末尾
  5. fh.seek(0) # 返回到开头
  6. print(fh.tell()) # 文件开头
  7. 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)

  1. with open(path) as fh:
  2. print(fh.tell()) # start of file
  3. print(fh.read()) # get everything and display it
  4. print(fh.tell()) # end of file
  5. fh.seek(0) # go back to the beginning
  6. print(fh.tell()) # start of file
  7. print(fh.read())

More detail in Python Documentation 7.2.1. Methods of File Objects

huangapple
  • 本文由 发表于 2023年6月2日 03:44:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76385216.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定