2016-03-04 130 views
1

我想從output.txt的線121-136讀取並保存在同一格式zxyr.txt.File看起來是這樣的:如何從特定行讀取文件並寫入輸出?

>ZYXR //74 
-6.440208621086e+03 -4.758666382870e+03 -3.995858566350e+03 -4.934315690511e+03 -5.049765912718e+03 
-4.323241464318e+03 -4.246930447741e+03 -3.836596391287e+03 -3.357569224670e+03 -2.955821531683e+03 
-2.579438902492e+03 -2.291910045847e+03 -1.831407086906e+03 -1.630707014227e+03 -1.376537942484e+03 

我的代碼

from __future__ import with_statement 

inFile = open('output.txt','r') 
outFile = open('zxyr.txt', 'w') 

lines=[121, 136] 
i=0 

for line in inFile: 
    if i in lines: 
     counter = str(int(inFile.read().strip()) 
     outFile.seek(0) 
     outFile.write(counter) 
    i+=1 

File "ex1.py", line 12 
    outFile.seek(0) 
     ^
SyntaxError: invalid syntax 

我的代碼有什麼問題?

回答

2

我想你將不得不閱讀所有以前的行。做什麼:

startline = 121 
endline = 136 
with open('output.txt','r') as inFile: 
    lines = inFile.readlines()[startline:endline+1] 

with open(zxyr.txt, 'w') as outFile: 
    outFile.writelines(lines) 
1

如下你可以寫工整地使用islice線的一個範圍:

from itertools import islice 

with open("output.txt", "r") as f_input, open("zxyr.txt", "w") as f_output: 
    f_output.writelines(islice(f_input, 121+1, 136+1)) 

要一對夫婦範圍的工作,你可以採取以下方法:

with open("output.txt", "r") as f_input, open("zxyr.txt", "w") as f_output: 
    for line_number, line in enumerate(f_input, start=1): 
     if (121 <= line_number <= 136) or (184 <= line_number <= 206): 
      f_output.write(line) 

這兩種解決方案都避免將整個文件讀入內存,如果文件很大,這很重要。

+0

我可以用這個多行間隔(121,136)螞蟻后者(184,206)? –

+0

不,不幸的是,這種方法適用於單一範圍,稍微不同的方法雖然可行,但我會更新。 –