Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how to read one line then delete that line ?  RSS feed

 
walter wang
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear All
I hv a question
if i hv a file and content of this file like belows
/* This is first line */
/* This is second line*/
I need read line by line, every time only could
read one line, and i need delete that line after
reading it.
How do I implement it?
Regards
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, there isn't really a direct way of deleting a single line from a file. You would basically have to overwrite the old file with a new file, which does not include the line you wish to delete. Which may well be more trouble than you want to go to. It sounds like you're going to eventually delete all lines from the file. If so, wouldn't it be easier to just delete the whole file when you're done?
Alternately, if you're only going to delete some lines, not others, then you could write a new file as you go. Each time you read a new line, decide if you want to "delete" it or not. If no, then write the line to the new file. If yes, then don't write that line. When you're done, the new file will contain only the lines you didn't want to delete. Now you can delete the original file, and rename the new file to have the name of the old one.
Yet another approach is to store the contents of the file in memory. Perhaps a LinkedList of Strings, where each element represents one line. Now you can add or remove lines as much as you want. When you're done, iterate through the modified List and write each line to a file, overwriting the original file you read from. This approach requires more memory than the previous "write as you go" approach - but it's useful if you want to be able to (for example) move backwards through a file. Which method makes more sense for you will depend on just what sort of processing you want to do with each line.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, this is really more appropriate for the I/O forum, so I'm moving it there...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!