Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否从文本文件中删除行?_Python - Fatal编程技术网

Python 是否从文本文件中删除行?

Python 是否从文本文件中删除行?,python,Python,我有一个textfile.txt,如下所示: First Line Second Line Third Line Fourth Line Fifth Line Sixth Line 如何才能最轻松地删除前三行和最后一行?没有Python解决方案,但由于您的问题是一个经典问题,因此我为您提供了一个sed解决方案 data="".join(open("textfile.txt").readlines()[3:-1]) open("newfile.txt","wb").write(data) $

我有一个textfile.txt,如下所示:

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

如何才能最轻松地删除前三行和最后一行?

没有Python解决方案,但由于您的问题是一个经典问题,因此我为您提供了一个sed解决方案

data="".join(open("textfile.txt").readlines()[3:-1])
open("newfile.txt","wb").write(data)
$ sed -n -e "4,5p" textfile.txt

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

此地址不使用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
此代码段将删除fie名称“file1.txt”中的前四行

$ awk 'NR>=4{if(p)print p;p=$0;}' file
Fourth Line
Fifth Line
f = open('file1.txt').readlines()

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