简体   繁体   English

替换 python 中文件的最后一行

[英]Replace the last line of a file in python

I am working on a project where i use a text file to store the data.我正在做一个项目,我使用文本文件来存储数据。 I have a label for the user to enter the name and i want the user's name to be saved on line 41 of the file, which is the last line.我有一个 label 供用户输入名称,我希望将用户名保存在文件的第 41 行,即最后一行。 I tried append but that just keeps adding a last line so if the user types another name it wont replace it but add another line.我尝试了 append 但它只是不断添加最后一行,因此如果用户键入另一个名称,它不会替换它,而是添加另一行。 Can you please help me modify the code so it writes the name in line 41 of the text file and if there is already something on the text file, it just replaces line 41 based on the input.你能帮我修改一下代码,让它在文本文件的第 41 行中写入名称吗?如果文本文件中已有内容,它只会根据输入替换第 41 行。 Until now i have this code but its not working i dont know why直到现在我有这段代码但它不起作用我不知道为什么

def addUser(self):
        global name
        global splitname
        name = self.inputBox.text()
        splitname = name.split()
        print("Splitname {}".format(splitname))
        print(len(splitname))
        self.usernameLbl.setText(name)
        self.inputBox.clear()
        # self.congratulations()
        if name != "":
                if len(splitname) == 2:
                        with open('UpdatedCourseInfo.txt', 'r', encoding='utf-8') as f:
                                data1 = f.readlines()
                        data1[40]= [f'\n{splitname[0]}, {splitname[1]}, 0, None, None']
                        with open('UpdatedCourseInfo.txt', 'w', encoding='utf-8') as f:
                                f.writelines()
                        f.close()
                else:
                        with open('UpdatedCourseInfo.txt', 'r', encoding='utf-8') as f:
                                data1 = f.readlines()
                        data1[40]= [f'\n{splitname[0]}, 0, 0, None, None']
                        with open('UpdatedCourseInfo.txt', 'w', encoding='utf-8') as f:
                                f.writelines()
                        f.close()
        print(name)
        return name

Here you go:给你go:


# == Ignore this part ==========================================================
# `create_fake_course_info_file`,  `FakeInputBox` and `FakeUsernameLabel` are just
# placeholder classes to simulate the objects that `FakeCls.addUser` method
# interacts with.

def create_fake_course_info_file(filepath: str):
    """Create a fake file to test ``FakeCls`` class implementation.

    Function creates a text file, and populates it with 50 blank lines.

    Parameters
    ----------
    filepath : str
        Path to the file to be created.
    """
    print(f"Saving fake data to: {filepath}")
    with open(filepath, "w") as fh:
        fh.write("\n" * 50)


class FakeInputBox:
    """
    Mock class with necessary methods to run ``FakeCls.addUser`` method.
    """
    def __init__(self, text):
        self._text = text

    def text(self):
        return self._text

    def clear(self):
        self._text = ""


class FakeUsernameLabel:
    """
    Mock class with necessary methods to run ``FakeCls.addUser`` method.
    """
    def setText(self, text):
        self.text = text

# == Actual Code ===============================================================

class FakeCls:

    def __init__(self, name):

        self.inputBox = FakeInputBox(name)
        self.usernameLbl = FakeUsernameLabel()

    def addUser(self):

        global name
        global split_name

        name = self.inputBox.text()
        split_name = name.split()
        print(f"Split Name: {split_name} | Length: {len(split_name)}")
        self.usernameLbl.setText(name)
        self.inputBox.clear()

        # self.congratulations()

        if name != "":
            # Read current contents of the file and save each line of text as
            # an element in a list.
            with open("UpdatedCourseInfo.txt", mode="r", encoding="utf-8") as fh:
                data = fh.readlines()
                # Replace the 41st line with the user's name.
                if len(split_name) == 2:
                    data[40] = f"\n{split_name[0]}, {split_name[1]}, 0, None, None"
                else:
                    data[40] = f"\n{split_name[0]}, 0, 0, None, None"
            # Write the updated list to the file.
            with open("UpdatedCourseInfo.txt", mode="w", encoding="utf-8") as fh:
                fh.writelines(data)
        print(name)
        return name

Example例子

Here's the code in action:这是实际的代码:

在此处输入图像描述

Notes笔记

I've made some changes to your original implementation, to make it a little bit cleaner and more "Pythonic".我对您的原始实现进行了一些更改,使其更简洁、更“Pythonic”。 You can ignore the code inside the create_fake_course_info_file function, FakeInputBox and FakeUsernameLabel classes as they're only placeholders to your actual code that was not provided in the question.您可以忽略create_fake_course_info_file function、 FakeInputBoxFakeUsernameLabel类中的代码,因为它们只是问题中未提供的实际代码的占位符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM