Python removing lines from a text file

Discussion in 'Mac Programming' started by Nsutton, Apr 24, 2010.

  1. macrumors member

    Nsutton

    Joined:
    Dec 29, 2009
    Location:
    6 Feet Under
    #1
    ok so, I want to have the bottom code to search that txt file find the line that contains the search criteria and then delete the line that contains the search criteria.



    Ideas?


    Code:
    if action2=='2':
    		fob=open('/Users/NSutton/Simple Adress/bookdata.txt','r')
    		searchdelete=raw_input("Enter the name of the contact you'd like to delete: ")
    		for line in fob:
    			if searchdelete in line:
        				print line
     
  2. macrumors 601

    HiRez

    Joined:
    Jan 6, 2004
    Location:
    Western US
    #2
    Instead of printing any line containing the search criteria, copy (append) any line that does not contain the search criteria to a destination file, or to memory. Essentially, you want to copy your source file line by line to a destination file, but skip any line where you find a match. If you want it to replace your source file, make the destination file a temp file, and when done, delete the source file and rename the temp file to the source file's name.
     
  3. thread starter macrumors member

    Nsutton

    Joined:
    Dec 29, 2009
    Location:
    6 Feet Under
    #3
    I understand in concept but am lost in actually putting that to code....
     
  4. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #4
    It seems like changing your if to say not in line, that would do it.

    -Lee
     

Share This Page