1

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.
Community
  • 1
  • 1
fighton
  • 23
  • 4
  • Possible duplicate of [Deleting a specific line in a file (python)](http://stackoverflow.com/questions/4710067/deleting-a-specific-line-in-a-file-python) – VMRuiz Jan 13 '17 at 11:54

2 Answers2

3

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.

Community
  • 1
  • 1
id5h
  • 206
  • 2
  • 9
  • You have a mistake on the link and it's not working. :) – VMRuiz Jan 13 '17 at 11:52
  • 1
    Thanks, apparently I can't copy&paste :) Should work now. – id5h Jan 13 '17 at 11:53
  • Already went there. shouldn't you be in read mode though if you want to make a for loop for it to work? – fighton Jan 13 '17 at 12:09
  • Nevermind, another answer worked! I ignored that before when I first encountered that thread because of the unfamiliar "truncate" and "seek" but now I tried it and it works now :) Will definitely familiarize myself with terms like those because I do not like copy pasting other people's code – fighton Jan 13 '17 at 12:21
  • I edited my answer to include a few lines that do what you want, based on the discussion in the link. I hope this helps :) – id5h Jan 13 '17 at 12:22
2

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.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Thank you, this works. I prefer this solution because it is much simpler and easier to understand. I wonder why I tried that some time but an error message appears because I cannot make a for loop work when in write mode. But now it works! I really don't know why. – fighton Jan 13 '17 at 12:52