I got a file with 100 lines. I want to delete line 26 till 49 so I did:
import os
l1 = []
with open(r"C:work001.txt", 'r') as fp:
l1 = fp.readlines()
with open(r"C:work001.txt", 'w') as fp:
for number, line in enumerate(l1):
if number not in list (range(25, 49)):
fp.write(line)
After doing this, the 26th line till 49th line are deleted. But now I want to add an empty line after the 25th line. How can I do that?
CodePudding user response:
A possible solution:
import os
l1 = []
with open(r"C:work001.txt", 'r') as fp:
l1 = fp.readlines()
with open(r"C:work001.txt", 'w') as fp:
for line in l1[:25]:
fp.write(line)
fp.write("\n")
for line in l1[49:]:
fp.write(line)
CodePudding user response:
You can write "\n"
. \n is an special character that represents a line jump.
CodePudding user response:
This task is simple because you already have the line number:
import os
l1 = []
with open(r"C:work001.txt", 'r') as fp:
l1 = fp.readlines()
with open(r"C:work001.txt", 'w') as fp:
for number, line in enumerate(l1):
if number not in list (range(25, 49)):
fp.write(line)
if number == 24:
fp.write('\n')
This code write an empty line after the 25th line, since the enumerate
function count starts from zero, so we check if number == 24
, and it's after you write the line
variable.