簡體   English   中英

替換 python 中文件的最后一行

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

我正在做一個項目,我使用文本文件來存儲數據。 我有一個 label 供用戶輸入名稱,我希望將用戶名保存在文件的第 41 行,即最后一行。 我嘗試了 append 但它只是不斷添加最后一行,因此如果用戶鍵入另一個名稱,它不會替換它,而是添加另一行。 你能幫我修改一下代碼,讓它在文本文件的第 41 行中寫入名稱嗎?如果文本文件中已有內容,它只會根據輸入替換第 41 行。 直到現在我有這段代碼但它不起作用我不知道為什么

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

給你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

例子

這是實際的代碼:

在此處輸入圖像描述

筆記

我對您的原始實現進行了一些更改,使其更簡潔、更“Pythonic”。 您可以忽略create_fake_course_info_file function、 FakeInputBoxFakeUsernameLabel類中的代碼,因為它們只是問題中未提供的實際代碼的占位符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM