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

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

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

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:

确定