简体   繁体   English

如何删除文本文件中的特定行?

[英]How to delete specific line in text file?

I'm making a joke program that has a text file storing jokes.我正在制作一个笑话程序,它有一个存储笑话的文本文件。 On program load, it grabs all the lines from the file and assigns them to a jokes list Everything but the remove joke function is working.在程序加载时,它从文件中获取所有行并将它们分配给一个笑话列表,除了删除笑话 function 之外的所有内容都在工作。 Whenever you call remove joke, it ends up re-writing every line in the text file to an empty string instead of the selected line每当您调用 remove joke 时,它最终会将文本文件中的每一行重写为一个空字符串,而不是选定的行

When running this function, it does remove the joke from the jokes list properly当运行这个 function 时,它确实从笑话列表中正确地删除了笑话

def remove_joke():
    for i in range(len(jokes)):
        print(f"{i}\t{jokes[i]}")
    
    remove_index = int(input("Enter the number of the joke you want to remove:\t"))

    with open("jokes.txt", "r") as f:
        lines = f.readlines()
    with open("jokes.txt", "w") as f:
        for line in lines:
            print(line)
            if line == jokes[remove_index]:
                f.write("")
    jokes.remove(jokes[remove_index])

Instead of代替

            if line == jokes[remove_index]:
                f.write("")

you want:你要:

            if line != jokes[remove_index]:
                f.write(line+'\n')

Or even:甚至:

            if line != jokes[remove_index]:
                print(line, file=f)

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

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