LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How do I remove a particular line in python without erasing the rest of the file? (https://www.linuxquestions.org/questions/programming-9/how-do-i-remove-a-particular-line-in-python-without-erasing-the-rest-of-the-file-4175412755/)

prox 06-21-2012 08:11 PM

How do I remove a particular line in python without erasing the rest of the file?
 
I want to learn Python so I started writing my first program which is a phone book directory.
It has the options to add a name and phone number, remove numbers, and search for them.
Ive been stuck on the remove part for about 2 days now and just can't get it working correctly. I've been in the Python IRC and everything, but haven't been able to figure it out.
Basically, my program stores the numbers to a list in a file. I cannot figure out how to remove a particular line in the file but keep the rest of the file intact. Can someone please help me with this?

Some people have advised that it will be easier to do if I create a temp file, remove the line, then copy the remaining lines from the original file over to the temp file. Then write over the original file over with the temp file. So I have been trying this...

http://bpaste.net/show/zusmRFYaBsAF09GUcKce/

dugan 06-22-2012 12:54 PM

Read the file into memory, remove the line, and then write it back.

Code:

with open('file.txt') as f:
    lines = f.readlines()
    del lines[3]

with open('file.txt', 'w') as f:
    f.write('\n'.join(lines))

That said, you should really be using SQLite for this. It's part of the standard library, as you can see here:

http://docs.python.org/library/sqlite3.html

Sure you'll need to learn the very basics of SQL, but SQLite will scale much better, and remain fast even when you have hundreds of megabytes worth of phone numbers.

Nominal Animal 06-22-2012 07:34 PM

Quote:

Originally Posted by dugan (Post 4709479)
when you have hundreds of megabytes worth of phone numbers.

What are you, a phone number pack rat? ;)

I was going to write something about the relative merits of SQLite versus flat files using Python fcntl.lockf() advisory file locking, but fortunately I noticed in time that this is for learning, not an I-need-this-tool case.

For a learning project, I too recommend Python + SQLite. SQLite will certainly come handy in many projects due to its versatility and ease of use.

I would, however, like to add a note of caution, prox. Because SQL tools are so handy, a lot of developers completely rely on them, ignoring all other approaches. Like they say, if your only tool is a hammer, all problems start to look like nails. Take care to learn other approaches, later, too. If for nothing else, then for widening your perspectives.


All times are GMT -5. The time now is 11:21 AM.