用python从文本文件中删除行

2024-05-19 02:09:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的textfile.txt:

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

我怎样才能去掉前三行和最后一行最舒服? 谢谢!


Tags: txtlinefirstsecondthirdtextfilefourthfifth
3条回答
lines = open('textfile.txt').readlines()
open('newfile.txt', 'w').writelines(lines[3:-1])

这个文件不使用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
data="".join(open("textfile.txt").readlines()[3:-1])
open("newfile.txt","wb").write(data)

相关问题 更多 >

    热门问题