如何从特定行读取文件并写入输出?

时间:2016-03-04 13:07:51

标签: python io

我想从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 个答案:

答案 0 :(得分: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 :(得分:1)

您可以使用make readonly/disable tinymce textarea非常干净地编写单行范围,如下所示:

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)

这两种解决方案都避免将整个文件读入内存,这在文件较大时非常重要。