Python类处理txtfiles

2024-04-27 04:37:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个名为“data”的类来处理(txt)文件到对象中的处理

它需要接受类变量“filename”,它将通过以下3个函数进行操作:

函数“init”:接收字符串并将其分配给类变量“filename”

函数“reset”:用类变量的名称生成一个新的空文件。现有文件将被覆盖

函数“save”:接收一个字符串并将其放在文件末尾

到目前为止,我的情况是:

class File:

    filename = []
    def __init__(self, filename):
        self.filename = filename

    def Reset (self, filename):
        self.filename = open('test.txt').close()

    def Save (self, input):
        self.input = raw_input()
        text_file = open("test.txt", "w")
        text_file.write(self.input)
        text_file.close()

我对编程非常陌生,已经试过自己一个人用word和几个小时的google,但我就是能´我不能让它工作。我将非常感谢任何帮助


Tags: 文件函数字符串texttestselftxtclose
1条回答
网友
1楼 · 发布于 2024-04-27 04:37:29

function "init": takes in a string and allocates it to the class variable "filename".

这个函数你已经做对了

function "reset": produces a new empty file with the name of the class variable. Existing files will be overwritten.

没有使用类变量打开文件,忘记了使用写入模式,并且重写了变量self.filename。正确:

    def Reset(self):
        open(self.filename, 'w').close()

function "save": takes in a string and puts it in the end of the file

您没有使用类变量来打开文件,您忘记了使用附加模式,并且我们不需要将给定的字符串存储在变量self.input中。正确:

    def Save(self, input):
        text_file = open(self.filename, "a")
        text_file.write(input)
        text_file.close()

相关问题 更多 >