Skip to main content
 首页 » 编程设计

python之使用 Python 将我的代码从 'readlines' 格式重写为 'for line in file' 格式

2025年05月04日15dudu

我有一个工作脚本可以从一系列巨大的文本文件中提取某些数据。不幸的是,我走上了“readlines”的道路,因此在处理了一定数量的文件后,我的代码内存不足。

我尝试重新编写我的代码以使用“for line in file”格式逐行处理文件,但是一旦找到字符串,我现在的行处理就会出现问题。

基本上,一旦找到我的字符串,我希望转到文本文件中的各种周围行,所以我希望回到之前的 16(以及 10 和 4)行并进行一些行处理以收集一些相关数据到搜索行。我用 readlines 路由枚举了文件,但我正在努力用逐行方法找出正确的方法(或者确实找出它是否可能!)。

这是我的代码,我承认我有一些糟糕的代码,因为我玩过一些抓线,基本上是在线 [-xx] 部分附近......

searchstringsFilter1 = ['Filter Used          : 1'] 
 
 
with open(file, 'r') as f: 
    for line in f: 
 
        timestampline = None 
        timestamp = None 
 
        for word in searchstringsFilter1: 
            if word in line: 
                #print line 
                timestampline = line[-16] 
                #print timestampline 
                keyline = line 
                Rline = line[-10] 
                print Rline 
 
                Rline = re.sub('[()]', '', Rline)    
                SNline = line[-4] 
                SNline = re.sub('[()]', '', SNline)  
 
                split = keyline.split() 
                str = timestampline 
                match = re.search(r'\d{2}:\d{2}:\d{2}.\d{3}', str) 
                valueR = Rline.split() 
                valueSN = SNline.split() 
 
                split = line.split() 
 
                worksheetFilter.write(row_num,0,match.group())  
                worksheetFilter.write(row_num,1,split[3], integer_format) 
                worksheetFilter.write(row_num,2,valueR[4], decimal_format) 
                worksheetFilter.write(row_num,3,valueSN[3], decimal_format) 
                row_num+=1 
                tot = tot+1 
                break 
 
    print 'total count for', '"',searchstringsFilter1[a],'"', 'is', tot 
    Filtertot = tot 
    tot = 0 

有什么明显的我做错了,或者我是否按照完全错误的路径去做我想做的事?

非常感谢您阅读本文, 米克格

请您参考如下方法:

你需要一个 circular buffer暂时将上一行保存在内存中。这可以使用 collections.deque 获得:

import collections 
 
ring_buf = collections.deque(maxlen=17) 
 
with open(file, 'r') as f: 
    for line in f: 
        ring_buf.append([line]) # append the new line and overwrite the last one 
                              # FIFO style 
 
        timestampline = None 
        timestamp = None 
 
        for word in searchstringsFilter1: 
            if word in line: 
                #print line 
                timestampline = ring_buf[-16] 
                #print timestampline 
                keyline = line 
                Rline = ring_buf[-10] 
                print Rline 
 
                Rline = re.sub('[()]', '', Rline)    
                SNline = ring_buf[-4] 
                SNline = re.sub('[()]', '', SNline)