脚本在读取文件时跳过了第二个for循环

3

我正在尝试读取日志文件并将某些值与预设阈值进行比较。我的代码可以通过函数中的第一个for循环记录原始数据。

我添加了打印语句以尝试弄清楚发生了什么,并且我已经得出结论,我的第二个for循环从未“发生”。

这是我的代码:

def smartTest(log, passed_file):    
    # Threshold values based on averages, subject to change if need be
    RRER = 5
    SER = 5
    OU = 5
    UDMA = 5
    MZER = 5
    datafile = passed_file
    # Log the raw data    
    log.write('=== LOGGING RAW DATA FROM SMART TEST===\r\n')
    for line in datafile:
        log.write(line)
        log.write('=== END OF RAW DATA===\r\n')

        print 'Checking SMART parameters...',
        log.write('=== VERIFYING SMART PARAMETERS ===\r\n')

        for line in datafile:
            if 'Raw_Read_Error_Rate' in line:
                line = line.split()
                if int(line[9]) < RRER and datafile == 'diskOne.txt':
                    log.write("Raw_Read_Error_Rate SMART parameter is: %s. Value under threshold. DISK ONE OK!\r\n" %int(line[9]))
                elif int(line[9]) < RRER and datafile == 'diskTwo.txt':
                    log.write("Raw_Read_Error_Rate SMART parameter is: %s. Value under threshold. DISK TWO OK!\r\n" %int(line[9]))
                else:
                    print 'FAILED'
                    log.write("WARNING: Raw_Read_Error_Rate SMART parameter is: %s. Value over threshold!\r\n" %int(line[9]))
                    rcode = mbox(u'Attention!', u'One or more hardrives may need replacement.', 0x30)

这是我调用此函数的方式:
dataOne = diskOne()
smartTest(log, dataOne)
print 'Disk One Done'

diskOne()看起来是这样的:

def diskOne():
    if os.path.exists(r"C:\Dejero\HDD Guardian 0.6.1\Smartctl"):
        os.chdir(r"C:\Dejero\HDD Guardian 0.6.1\Smartctl")
        os.system("Smartctl -a /dev/csmi0,0 > C:\Dejero\Installation-Scripts\diskOne.txt")
        # Store file in variable
        os.chdir(r"C:\Dejero\Installation-Scripts")
        datafile = open('diskOne.txt', 'rb')
        return datafile
    else:
        log.write('Smart utility not found.\r\n')

我已经尝试通过谷歌搜索类似的问题,但没有找到。我尝试将我的第一个for循环移动到diskOne()中,但是仍然出现了同样的问题。没有语法错误,但是目前我无法看出问题所在。

1个回答

8

它没有跳过你的第二个循环。你需要将位置seek回去。这是因为读取文件后,文件偏移量将被放置在文件结尾处,因此您需要将其放回开头。可以通过添加一行轻松完成此操作。

datafile.seek(0);

在第二个循环之前。

参考:文档


虽然这个答案还可以,也许你应该添加另一种将整个第二个文件存储在内存中并每次迭代它的方法——如果第二个文件的数据适合内存——因为它不涉及文件,所以应该更快。 - user202729

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接