为何调用Python类方法仅能打印文本文件内容一次?
问题原因与解决方案
问题原因
文件对象内部维护着读写指针,第一次调用output()时,for line in self.fileobject会把指针从文件开头逐步移动到末尾,读完所有内容。第二次调用时,指针已经停在文件末尾,没有剩余内容可以读取,所以不会有任何输出。你之前误以为for循环不会改动文件对象,实际上它会改变指针的位置。
解决方案
有两种常用的修复方式:
方式一:每次输出前重置文件指针
在output()方法开头调用seek(0),将指针重新移回文件起始位置:
class Datei(): def __init__(self, filename): self.fileobject = open(filename) def output(self): self.fileobject.seek(0) # 重置文件指针到开头 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()
这种方式适合处理大文件,不会占用过多内存,但每次输出都会重新读取磁盘文件。
方式二:初始化时读取文件内容到内存
在__init__阶段就把文件内容全部加载到内存,后续输出直接遍历内存中的内容:
class Datei(): def __init__(self, filename): # 用with语句自动关闭文件,避免资源泄漏 with open(filename) as f: self.lines = [line.rstrip() for line in f] def output(self): for line in self.lines: print(line) def end(self): pass # 因with已自动关闭文件,此处可留空或移除该方法 file = Datei("yellow_snow.txt") file.output() print("second try") file.output() file.end()
这种方式适合小文件,输出速度更快,无需重复读取磁盘,但会将整个文件内容加载到内存中。
内容的提问来源于stack exchange,提问作者Dirk
相关产品推荐
相关产品推荐

