How to change a specific line in a file, depending on chosen name?

后端 未结 3 1522
轻奢々
轻奢々 2021-01-21 22:41

I have a text file where i have numbers and names listed. each number belongs to a specific name, and they belong on the same line. the content of the file, looks like this:

3条回答
  •  不要未来只要你来
    2021-01-21 23:03

    As some of the comments suggested, you can't acces specific lines of a textfile. The approaches you have tried so far, do replace text in strings, like you want, but the string you are modifying don't have any link to the file anymore.

    You have to read your hole file in memory instead. Make your desired changes, and then write everything back to the file.

    lines = []
    with open("MyFile.txt", 'r')as MyFile:
        for line in MyFile.readlines():
            lines.append(line)
    
    for index, line in enumerate(lines):
        if line.startswith("Kari"):
            lines[index] = "Kari 1881\n"
    
    with open("MyFile.txt", "w+") as MyFile:
        MyFile.writelines(lines)
    

    This example works for this specific case. I'll leave the challenge of generalizing it up to you.

提交回复
热议问题