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

Script skips second for loop when reading a file

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

我已经添加了 print 语句来尝试弄清楚发生了什么,并且我已经设法推断出我的第二个 for 循环永远不会 "happens"。

这是我的代码:

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')

我尝试用谷歌搜索与我的类似的问题,并找到了 none。我尝试将我的第一个 for 循环移动到 diskOne() 但同样的问题发生了。没有语法错误,我只是现在看不到问题。

它没有跳过你的第二个循环。您需要seek 位置回来。这是因为读取文件后,文件偏移量会放在文件的末尾,所以你需要把它放回开头。这可以通过添加一行

轻松完成
datafile.seek(0);

在第二个循环之前。

参考:Documentation