Deleting a line from a file in Python

后端 未结 5 2085
离开以前
离开以前 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:17

    You can use regex.

    import re
    if not re.match("^tom$", line):
        output.append(line)
    

    The $ means the end of the string.

    0 讨论(0)
  • 2020-12-05 21:18

    That's because

    if not "tom" in line
    

    checks, whether tom is not a substring of the current line. But in tom1, tom is a substring. Thus, it is deleted.

    You probably could want one of the following:

    if not "tom\n"==line # checks for complete (un)identity
    if "tom\n" != line # checks for complete (un)identity, classical way
    if not "tom"==line.strip() # first removes surrounding whitespace from `line`
    
    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 2020-12-05 21:22

    I'm new in programing and python (a few months)... this is my solution:

    import fileinput
    
    c = 0 # counter
    for line in fileinput.input("korrer.csv", inplace=True, mode="rb"):
        # the line I want to delete
        if c == 3: 
            c += 1
            pass
        else:
            line = line.replace("\n", "")
            print line
            c +=1
    

    I'm sure there is a simpler way, just it's an idea. (my English it's not very good looking!!)

    0 讨论(0)
  • 2020-12-05 21:27

    change the line:

        if not "tom" in line:
    

    to:

        if "tom" != line.strip():
    
    0 讨论(0)
提交回复
热议问题