如何替换不在当前循环Python中的文本文件中的一行

Posted

技术标签:

【中文标题】如何替换不在当前循环Python中的文本文件中的一行【英文标题】:How do I replace a line in a text file thats not in the current loop Python 【发布时间】:2021-07-23 13:41:44 【问题描述】:

我是编程新手,所以如果有更简单的方法可以解决这个问题,请告诉我。有一个名为 Duelist.txt 的文本文件,其中包含以下内容:

-------------------------------------------------
Duelist: Seto Kaiba
Server: Amazon
Username: Kaibaman
Password: Blue-Eyes White Dragon
-------------------------------------------------
Duelist: Mokuba Kaiba
Server: Amazon
Username: Kaibaboy
Password: KaibabestBro
------------------------------------------------

如果loginexistsTRUE,则此changeUsername(login,duelistID,exists,server): 函数运行。如果他们想更改用户名,它会提示用户输入新的用户名,然后函数supposed 可以在当前位置后两行的Duelist.txt 中更改用户名,但事实并非如此。 ..

def changeUsername(login,duelistID,exists,server):
    index = 0
    username = "Username: "
    serverSearch = []
    duel = "Duelist: " + duelistID
    search = "Server: " + server
    if login == True and exists ==True:
        print("Would you like to change this username for " + server + "?")
        print("Press \"y\" key for yes or press \"n\" key for no followed by the Enter key")
        choice = input(f'duelistID:')

        if choice == "y":
            newUsername = input("Please enter new username: ")
            username += newUsername
            with open("Duelist.txt", 'r') as file:
                content = file.readlines()

                for line in content:
                    serverSearch.append(line.strip("\n"))

            with open("Duelist.txt", 'r+') as file:
                for index, line in enumerate(serverSearch):
                    if duel in line:
                        if search == serverSearch[index+1]:
                            serverSearch[index+2] = username
                            file.write(line.replace(serverSearch[index+2], username))
                            

            if choice == "n":
                pass
        
            print("Exiting Edit Server Username...")
            time.sleep(1)

这是函数changeUsername(login,duelistID,exists,server)中的用户输入 loginexists 为 True,duelistID 为 Mokuba Kaiba,server 为 Amazon。

Would you like to change this username for Amazon?
Press "y" key for yes or press "n" key for no followed by the Enter key
Mokuba Kaiba:y
Please enter new username: Mokuba
Exiting Edit Server Username...

用户输入后,我在Duelist.txt 中得到以下信息

Duelist: Mokuba Kaiba---------------------------
Duelist: Seto Kaiba
Server: Amazon
Username: Kaibaman
Password: Blue-Eyes White Dragon
-------------------------------------------------
Duelist: Mokuba Kaiba
Server: Amazon
Username: Kaibaboy
Password: KaibabestBro
-------------------------------------------------

我很难弄清楚这一点并提出一个简单的解决方案,但我只是一个拥有四流代码的三流编码器。谁能帮助这个函数做它应该做的事情?

【问题讨论】:

编辑文本文件的规则是,您应该读取一个文件,将原始或修改的行写入新文件,然后用原始名称重命名新文件。你可以看看***.com/q/55030437/3545273 或***.com/q/16604826/3545273 谢谢!我将在我未来的节目中坚持这一规则。感谢您的帮助! 【参考方案1】:

试试这个:

def changeUsername(login,duelistID,exists,server):
    index = 0
    username = "Username: "
    serverSearch = []
    duel = "Duelist: " + duelistID
    search = "Server: " + server
    if login == True and exists ==True:
        print("Would you like to change this username for " + server + "?")
        print("Press \"y\" key for yes or press \"n\" key for no followed by the Enter key")
        choice = input(f'duelistID:')

        if choice == "y":
            newUsername = input("Please enter new username: ")
            username += newUsername
            with open("Duelist.txt", 'r') as file:
                content = file.readlines()

            for line in content:
                serverSearch.append(line.strip("\n"))

            for index, line in enumerate(serverSearch):
                if duelistID in line:
                    serverSearch[index]=(serverSearch[index]).replace(duelistID,newUsername)

            with open("Duelist.txt","w") as file:
                file.write('\n'.join(serverSearch))

            if choice == "n":
                pass

            print("Exiting Edit Server Username...")

changeUsername(True,"Kaibaman",True,"Amazon")

我个人更喜欢将整个文本文件加载到列表中,进行所需的更改并将整个列表写回文件。

【讨论】:

非常感谢!您让我克服了障碍,我对您的答案进行了一些修改,以使该功能按我的意愿工作!非常感谢您的帮助,我刚刚启动了我的堆栈溢出帐户,所以我很高兴这里有像你这样的很棒的人!【参考方案2】:

我认为我需要重新表述我的问题,但 Pervez 能够根据我的需要进行必要的更改。我只是添加了一些调整来提出以下内容:

def changeUsername(login,duelistID,exists,server):
    index = 0
    username = "Username: "
    serverSearch = []
    duel = "Duelist: " + duelistID
    search = "Server: " + server
    if login == True and exists ==True:
        print("Would you like to change this username for " + server + "?")
        print("Press \"y\" key for yes or press \"n\" key for no followed by the Enter key")
        choice = input(f'duelistID:')

        if choice == "y":
            newUsername = input("Please enter new username: ")
            username += newUsername
            with open("Duelist.txt", 'r') as file:
                content = file.readlines()

            for line in content:
                serverSearch.append(line.strip("\n"))

            for index, line in enumerate(serverSearch):
                if duelistID in line:
                    if search == serverSearch[index+1]:
                        serverSearch[index+2]=(serverSearch[index+2]).replace(serverSearch[index+2],username)

            with open("Duelist.txt","w") as file:
                file.write('\n'.join(serverSearch))

            if choice == "n":
                pass

            print("Exiting Edit Server Username...")

在这种情况下,如果函数可以匹配 duelistIDsearch 行,函数只会替换 Duelist.txt 中的文本。希望我解释得对。

【讨论】:

以上是关于如何替换不在当前循环Python中的文本文件中的一行的主要内容,如果未能解决你的问题,请参考以下文章

Python:如何替换pdf中的文本

如何搜索和替换文件中的文本?

python 替换当前剪贴板条目中的文本[Python 2.7]适用于Win8.1x64

如何将查找和替换限制为仅 CSV 中的一列?

我们如何使用Windows Powershell脚本替换文本文件中的日期?

如何在 Python 中搜索和替换文件中的文本?