2010-01-14 94 views

回答

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

沒有Python的解決方案,但因爲你的問題是一個經典,我爲您呈現SED解決方案。

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

當然的地址4,5只適用於你的準確輸入所需的輸出:)

+0

但有一個很簡單的Python解決方案... – tkbx 2012-12-12 16:20:18

13

這一個不使用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 
1
f = open('file1.txt').readlines() 

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

此代碼段將刪除外商投資企業名稱「FILE1.TXT」前四線