Skip to main content
 首页 » 编程设计

python之通过类中的函数反转文本文件的行

2025年05月04日36zfyouxi

我正在尝试创建一个在构造函数中接收文件名并具有反转该文件中所有行的函数的类。

class exampleOne: 
    def __init__(self, fileName): 
        self.fileName = fileName 
 
    def reverse(self): 
        file = open(self.fileName, "w") 
        for value in list: 
            file.write(value.rstrip() + "\n") 
        file.close() 
 
a = exampleOne("textExample.txt") 
a.reverse() 
 
Text file: 
1. 
2. 
3. 
The output i want in the existing file: 
3. 
2. 
1. 

但是当我尝试运行它时,我得到了这个错误: “TypeError:'type' 对象不可迭代”。提前致谢

请您参考如下方法:

这个声明:

for value in list: 

指的是一个叫做 list 的东西,但是在你的程序中没有那个名字的东西。如果没有本地定义,list 指的是内置的 Python 类型 list,您不能像在 for 循环中那样使用它.

避免重新定义内置 Python 对象(如 list)的名称通常是个好主意。在您的情况下,您可以使用 lines 来表示文件中的行列表。

(您还必须添加代码才能真正读取文件中的行。)