Best way to Delete lines from a file inline

101 views
Skip to first unread message

sujay hegde

unread,
May 26, 2015, 3:03:18 AM5/26/15
to python-g...@googlegroups.com
Hello Guys,
    I want to delete 10,100 from a file inline(Linux Environment).
    Right now I am using the sed command (ie sed  --in-place 10,100d filename.txt)
    I wanted to know a way to do it using python module. I tried using fileupdate module, but it wasnt of help.

Thanks and Regards,
Sujay Hegde

Robert Mandić

unread,
May 27, 2015, 8:38:26 AM5/27/15
to python-g...@googlegroups.com
Inline sed and inline perl modes are actually opening a temporary file in write mode and then copy al the lines that you wanted into the temporary file filtering out the ones that you don't want and then moving the new file in place of the old one:

$ sed -i '/localhost/d' /etc/hosts
sed: couldn't open temporary file /etc/sed1awUIL: Permission denied

As you can see I cannot modify /etc/hosts because it is owned by root and therefore I cannot modify it. Just a demonstration that sed is creating a new temporary file.

The way you can do this in python is to:
1) open original file in read mode
2) open a temp file in write mode
3) loop through all the lines in original file and write the ones you want into your temp file
4) close both file handles
5) move your temp file in place of your original file

In your case you just need a variable that counts how may lines you have alreadfy read in order to write only the ones you want into your temp file.

--
You received this message because you are subscribed to the Google Groups "Python GCU Forum" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python-gcu-for...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Lp, Robert
Reply all
Reply to author
Forward
0 new messages