简体   繁体   中英

How to delete lines from a text file?

How can I make this work to delete values from my txt file?
I have an 11 line file of 4 digit numbers, I can add but am stuck on deleting.

def delete_file(string_in):
    print("deleted_from_file")
    with open('test.txt', 'a+') as f:
        d = f.readlines()
        f.seek(11)
        for i in d:
            if i != " item = {} ":
            f.write(i)

    f.close()

a+ mode means to write at the end of the file. So the seek has no effect, it always writes the lines after all the existing lines.

It would be easier to just open the file separately for reading and writing. Otherwise you also need to truncate the file after all the writes.

BTW, you don't need to use f.close() when you use with -- it automatically closes (that's the whole point).

The lines returned by readlines() end with newlines, you need to strip those off before comparing with the string.

def delete_file(string_in):
    print("deleted_from_file")
    with open('test.txt', 'r') as f:
        d = f.readlines()
    with open('test.txt', 'w') as f:
        for i in d:
            if i.rstrip('\n') != " item = {} ":
                f.write(i)

You can store all the needed lines into a list using a list comprehension,
and then write the lines into the file again after the file empties out:

def delete_file(string_in):
    print("deleted_from_file")
    with open('test.txt', 'r') as f:
        d = [i for i in f if i.strip('\n') != " item = {} "]
    with open('test.txt', 'w') as f:
        f.write(''.join(d))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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