For example, we have some file like that:
first line second line third line
And in result we have to get:
first line second line third line
Use ONLY python
Delete multiple lines from a file by line numbers Read contents from an original file line by line and for each line, Keep track of line number. If the line number of the current line matches the line number in the given list of numbers, then skip that line, else add the line in the temporary / dummy file.
The with
statement is excellent for automatically opening and closing files.
with open('myfile','rw') as file: for line in file: if not line.isspace(): file.write(line)
import fileinput for line in fileinput.FileInput("file",inplace=1): if line.rstrip(): print line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With