从文本文件中删除行?

24

我有一个类似这样的文本文件textfile.txt:

First Line
Second Line
Third Line
Fourth Line
Fifth Line
Sixth Line

如何最舒适地删除前三行和最后一行?

5个回答

42
with open('textfile.txt') as old, open('newfile.txt', 'w') as new:
    lines = old.readlines()
    new.writelines(lines[3:-1])

19

这个例子没有使用 readlines(),因此对于更大的文件尺寸来说是理想的。

numline=3 #3 lines to skip
p=""
o=open("output.txt","a")
f=open("file")
for i in range(numline):
    f.next()
for line in f:
    if p:
        o.write(p)
    p=line
f.close()
o.close()

既然有sed的答案,这里是一个awk的答案

$ awk 'NR>=4{if(p)print p;p=$0;}' file
Fourth Line
Fifth Line

5
data="".join(open("textfile.txt").readlines()[3:-1])
open("newfile.txt","wb").write(data)

1
f = open('file1.txt').readlines()

open('file1.txt', 'w').writelines(lines[4:])

这段代码将从文件名为"file1.txt"的文件中删除前四行。

应该是 f = open('file1.txt').readlines()然后使用 open('file1.txt', 'w').writelines(f[4:]) - quarkz

-4

虽然没有 Python 的解决方案,但由于您的问题是经典问题,我向您介绍一个 sed 解决方案。

$ sed -n -e "4,5p" textfile.txt

当然,地址4,5只适用于您的输入和所需的输出 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接