如何在文本文件中的某个行号之后添加一个空行?
How can I add an empty line after a certain linenumber within a text file?
我得到了一个 100 行的文件。我想删除第 26 行到第 49 行,所以我做了:
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)
这样做之后,第26行到第49行被删除。但是现在我想在第 25 行之后添加一个空行。我该怎么做?
你可以写"\n"
。 \n是一个特殊字符,代表行跳转。
可能的解决方案:
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)
这项任务很简单,因为您已经有了行号:
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')
这段代码在第25行之后写了一个空行,因为enumerate
函数计数从零开始,所以我们检查if number == 24
,并且是在你写完line
变量之后.
我得到了一个 100 行的文件。我想删除第 26 行到第 49 行,所以我做了:
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)
这样做之后,第26行到第49行被删除。但是现在我想在第 25 行之后添加一个空行。我该怎么做?
你可以写"\n"
。 \n是一个特殊字符,代表行跳转。
可能的解决方案:
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)
这项任务很简单,因为您已经有了行号:
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')
这段代码在第25行之后写了一个空行,因为enumerate
函数计数从零开始,所以我们检查if number == 24
,并且是在你写完line
变量之后.