0

I have a file A having content as follows

line1
line2
line3
line4
line5
  1. I read file A

  2. I copy file A content to new file B from line 4

  3. At the output I need file A as,

    line1
    line2
    line3
    

    and file B as

    line4
    line5
    

I have a code that copies line from A to B but can't figure out how to delete it after writing it to other file ?

Ben Blank
  • 54,908
  • 28
  • 127
  • 156
Rahul
  • 69
  • 6
  • This isnb't a free programming site. This is the most basic of programming problems. Give it a try yourself. Show us what you've tried if it isn't working out for you. – CryptoFool Feb 26 '19 at 20:41
  • You need to rewrite file A, containing only the lines you want in it. – mkrieger1 Feb 26 '19 at 20:44
  • Thank you mkrieger, will try that – Rahul Feb 26 '19 at 20:45
  • @mkrieger1: Or if they can uniquely identify the split point at the time they reach it, they could use `tell` to remember where it was, and after copying the data to file B, `seek` back and then call `truncate` (which avoids needing to rewrite the file at all). Assumes the data to "move" is always at the end of the file of course. – ShadowRanger Feb 26 '19 at 20:46
  • @ShadowRanger I agree. Still... – mkrieger1 Feb 26 '19 at 20:47
  • 1
    Possible duplicate of [using Python for deleting a specific line in a file](https://stackoverflow.com/questions/4710067/using-python-for-deleting-a-specific-line-in-a-file) – mkrieger1 Feb 26 '19 at 20:47

1 Answers1

0

If you can identify when you're at the split point (the point where the data to stay in file A ends, and the data to move in file B begins), and the data to move is "the rest of the file", the best approach is to truncate file A after copying the excess data.

Pseudo-code for it would be:

moving = False
splitpoint = None
for line in infile:  # infile must have been opened in r+ mode to allow modification
    if moving:
        outfile.write(line)
    elif should_start_moving():
        # Assumes you know you're at the split point when you have read line 3,
        # before you see line 4
        splitpoint = infile.tell()  # Save off split point
        moving = True

# If we ever reached the splitpoint, we want to truncate what we moved
if splitpoint is not None:
    infile.seek(splitpoint)  # Go back to where we saw the split point
    infile.truncate()        # Cut off the rest of the file
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271