简体   繁体   English

从文本文件中删除行?

[英]Remove lines from a textfile?

I have a textfile.txt like this:我有一个像这样的 textfile.txt:

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

How can I remove the first three lines and the last line most comfortable?如何去除前三行和最后一行最舒服?

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

This one doesn't use readlines() so it is ideal for bigger sized files.这个不使用 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()

Since there's a sed answer, here's an awk one由于有一个 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)
f = open('file1.txt').readlines()

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

This code snippet will delete first four line from fie name "file1.txt"此代码段将从文件名称“file1.txt”中删除前四行

No Python solution but since your problem is a classic, I present you a sed solution.没有 Python 解决方案,但由于您的问题很经典,因此我为您提供了一个 sed 解决方案。

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

Of course the address 4,5 only works for exactly your input and required output :)当然,地址4,5仅适用于您的输入和所需的输出:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM