Deleting a line from a file in Python

后端 未结 5 2089
离开以前
离开以前 2020-12-05 20:27

I\'m trying to delete a specific line that contains a specific string.

I\'ve a file called numbers.txt with the following content:

5条回答
  •  星月不相逢
    2020-12-05 21:18

    Just for fun, here's a two-liner to do it.

    lines = filter(lambda x:x[0:-1]!="tom", open("names.txt", "r"))
    open("names.txt", "w").write("".join(lines))
    

    Challenge: someone post a one-liner for this.

    You could also use the fileinput module to get arguably the most readable result:

    import fileinput
    for l in fileinput.input("names.txt", inplace=1):
        if l != "tom\n": print l[:-1]
    

提交回复
热议问题