2010-01-14 3 views
17

와 TEXTFILE에서 줄을 제거 :내가 이런는 TextFile.txt가 파이썬

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

가 어떻게 가장 편안 처음 세 줄과 마지막 줄을 제거 할 수 있습니까? 감사합니다.

답변

32
lines = open('textfile.txt').readlines() 
open('newfile.txt', 'w').writelines(lines[3:-1]) 
4
data="".join(open("textfile.txt").readlines()[3:-1]) 
open("newfile.txt","wb").write(data) 
-3

아니 파이썬 솔루션하지만 문제는 고전이기 때문에, 나는 당신에게 SED 솔루션을 제시한다. 주소 4,5 만 정확히 입력 및 필요한 출력 : 작동 물론

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

+0

을 "은 File2.txt"저런 이름에서 처음 네 줄을 삭제합니다에게있어하지만이 매우 간단한 Python 솔루션 ... – tkbx

13

이 하나의 readlines()를 사용하지 않습니다 그래서 더 큰 크기의 파일에 이상적입니다. sed를 답이 거기에 있기 때문에

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() 

는 여기 AWK 하나

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

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

이 코드는

관련 문제