简体   繁体   中英

How do I remove an entire line with a specific word, from a text file?

I made a text file called contacts.txt which contains:

pot 2000

derek 45

snow 55

I want to get user input (a name) on which contact to remove, and delete the entire line containing that name. So far, this is what I've done:

# ... previous code
if int(number) == 5:
    print "\n"
    newdict = {}
    with open('contacts.txt','r') as f:
        for line in f:
            if line != "\n":
                splitline = line.split( )
                newdict[(splitline[0])] = ",".join(splitline[1:])
    print newdict
    removethis = raw_input("Contact to be removed: ")
    if removethis in newdict:
        with open('contacts.txt','r') as f:
            new = f.read()
        new = new.replace(removethis, '')
        with open('contacts.txt','w') as f:
            f.write(new)

When I enter "pot", I come back to the text file and only "pot" is removed, the "2000" stays there. I tried

new = new.replace(removethis + '\\n', '') as other forums suggested, but it didn't work.

Notes:

  • Everything I've read on other forums requires me to make a new file, but I don't want that; I only want one file.
  • I already tried 'r+' the first time I opened the file and inserted a for loop which only picks the lines that do not contain the input word, but it doesn't work either.

I saw you said this is not a duplicate, but isn't this discussion equivalent to your question?

Deleting a specific line in a file (python)

Based on the discussion in the link, I created a .txt file from your input (with the usernames you supplied) and ran the following code:

filename = 'smp.txt'

f = open(filename, "r")
lines = f.readlines()
f.close()

f = open(filename, "w")
for line in lines:
  if line!="\n":
    f.write(line)
f.close()

What this does is to remove the spaces between the lines. It seems to me as if this is what you want.

How about this:

  • Read in all the lines from the file into a list
  • Write out each line
    • Skip the line that you want removed

Something like this:

filename = 'contacts.txt'
with open(filename, 'r') as fin:
    lines = fin.readlines()
with open(filename, 'w') as fout:
    for line in lines:
        if removethis not in line:
           fout.write(line)

If you want to be more precise about the line you remove, you could use if not line.startswith(removethis+' ') , or you could put together a regular expression of some kind.

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