如何在文本文件中的特定行号后添加空行?
我得到了一个有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行之后添加一条空线。我该怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个可能的解决方案:
A possible solution:
这个任务很简单,因为您已经有了行号:
此代码在第 25 行之后写入一个空行,因为
enumerate
函数计数从零开始,因此我们检查if number == 24
,它是在您写入line
变量之后。This task is simple because you already have the line number:
This code write an empty line after the 25th line, since the
enumerate
function count starts from zero, so we checkif number == 24
, and it's after you write theline
variable.您可以编写
“ \ n”
。 \ n 是一个特殊的角色,代表线跳跃。You can write
"\n"
. \n is an special character that represents a line jump.