Skip to content Skip to sidebar Skip to footer

Delete A Line From A File In-place

I have a .txt and i want a python script to do something with it. My .txt looks something like this: 27b23815-4cbb-dfae-3e6d-38f67ec4266e 81a090bd-8973-bc37-5c7b-dc1a18e8ddee 7e1b

Solution 1:

Since the file paradigm is a (resizable) array of bytes, you cannot simply delete data from inside. Instead, you do either of the following:

  • slide back all the data following the fragment to be deleted to overwrite it, then adjust the file's size (old-fashioned, typically used with memory-mapped files or when you can't afford another copy of the data)
  • write all the resulting data to a new file, then move it over the old one (typical in batch processing since move is atomic and instant within the same filesystem, may work (depending on the OS) even if the file is open by something else, and you can check the results before applying the change)
  • read all the data you need to preserve into memory, then truncate the file to zero bytes and write the new data (typical for text editors. The file cannot be open for writing by something else and the moment you truncate it, the old contents are lost. OTOH, you don't need the permissions to create another file and overwrite this one)

As for list manipulations, RTM Sequence types.

Solution 2:

I figured it out! Now that i see it, it is pretty simple

 f = open('file','r')  
 lines = f.readlines()
 iflines[5]: del lines[0]

Post a Comment for "Delete A Line From A File In-place"