Skip to main content
 首页 » 编程设计

python之如何在 python 中读取从第 7 行到第 265 行的行

2025年05月04日14findumars

我正在读取一个 .txt 文件,但我想从第 6 行到第 265 行读取文件。有人能告诉我该怎么做吗? 输出.txt :

my code: 
 
    h = httplib.HTTPSConnection(host, port) 
 
h.set_debuglevel(1) 
 
headers = { 
 
    "Content-Type": "multipart/form-data; boundary=%s" % (boundary,), 
 
    "Connection": "Keep-Alive", 
 
} 
 
h.request('POST', uri, body, headers) 
 
res = h.getresponse() 
filehandle = open("Output.txt", "wb") 
filehandle.write(res.read()) 
import itertools 
with open("Output.txt", "rb") as infile, open("output1.txt", "wb") as outfile: 
    for line in itertools.islice(infile, 6, 265): 
        outfile.write(line) 
filehandle.close() 

上面的代码只是读取第 6 行,但是如何从第 6 行读取到第 265 行?

请您参考如下方法:

我建议使用 itertools 包中的 islice。

import itertools 
 
 with open("input.txt", "rb") as infile, open("output.txt", "wb") as outfile: 
     for line in itertools.islice(infile, 6, 265): 
         outfile.write(line) 

为了响应您要求将前 6 个和最后 12 个读入一个文件,并将其余部分读入另一个文件的评论,我将执行如下操作

from collections import deque 
from itertools import islice  
 
with open("input.txt", "rb") as infile, open("output1.txt", "wb") as outfile1, open("output2.txt", "rb") as outfile2: 
    outfile.write(''.join(islice(infile, 6))) 
 
    q = deque(islice(infile, 12)) 
    outfile2.write(''.join(q)) 
 
    for line in infile: 
        q.append(line) 
        outfile2.write(q.popleft()) 
 
    outfile.write(''.join(q)) 

这里的想法是

  1. 将前6行写入第一个文件
  2. 将接下来的 12 行写入第二个文件并用它们填充队列
  3. 将新行插入队列并弹出旧行,直到输入文件耗尽
  4. 将队列中剩余的 12 行(最后 12 行)写入第一个输出文件。