Skip to main content
 首页 » 编程设计

python之遍历文件中的行会产生错误的行数

2025年05月04日14del

我正在慢慢熟悉 Python,但在我认为是一个简单脚本的过程中遇到了一个主要障碍。

可编程红外线 Remote 以称为 ProntoEdit HEX 的文件格式存储其红外线代码。这本质上是一个长文件,文件中的每一行代表特定 IR 代码的数据。数据以十六进制数字表示,每个数字之间有一个空格。我已经编辑了文件,所以每一行只包含十六进制数字,每行之间有一个空格(十六进制数字之前没有 0x)。每行有 64 个十六进制数。它们成对出现,因此每行包含 32 对。为了将数据转换为简单的二进制字符串,您将每对中的第二个数字除以第一个数字,根据比率,它要么是 1 要么是 0。

希望您已经了解了所有内容。我设法用 Python 编写了一个脚本来为我自动执行此操作,因为我开始使用的文件中有 768 行。该脚本似乎可以正常工作,但由于某种原因,它只执行了文件的一半,然后就停止了。它似乎也跳过了文件的第一行。我已经手动检查过,它从第二行正确地“解码”到文件的一半,即第 384 行。我不知道为什么会这样。

这是(相对)简单的脚本:

rawcode = open(r"stripped.txt", "r") 
outputfile = open(r"output_codes.txt", "w") 
currentline = 0 
for lines in rawcode: 
    output = [] #empty list for output 
    line = rawcode.readline() 
    splitline = line.split(" ") #turn the line into a list 
    splitline.remove('\n') 
 
    y = 0 
    for x in list(range(32)): #go through each pair in the line 
        num1 = int(splitline[y], 16) 
        num2 = int(splitline[y+1], 16) 
        if (num2 / num1) == 3: 
            output.append("0") 
        elif (num2 / num1) == 7: 
            output.append("1") 
        y += 2 
 
    print(output) 
    outstring = ''.join(output) 
    outputfile.write(outstring) 
    outputfile.write("\n") 
    currentline += 1 
    print(currentline) 
 
outputfile.flush() 
outputfile.close() 
rawcode.close() 

另外,这是输入文件和我得到的输出文件的链接。

stripped.txt

output.txt

如果有人有以这种方式处理文件的经验,非常感谢您的帮助!我真的不熟悉 Python 的复杂性——你可能会说,我有 C 背景,并且仍在为两种语言的不同哲学而苦苦挣扎。

请您参考如下方法:

你在这里进行了复读:

for lines in rawcode: 
    output = [] #empty list for output 
    line = rawcode.readline() 

不清楚您要完成什么,因为您对流程的描述毫无意义。 (它可能很准确,但仍然没有意义:除法然后舍入为 1 或 0?)

好的,这似乎可行:

#!python3 
 
with open('stripped.txt') as infile, open('output.txt', 'w') as outfile: 
    for line in infile: 
        line = line.strip() 
        if not line: 
            continue 
 
        hexnums = [int(hn, 16) for hn in line.split()] 
        for num1, num2 in zip(hexnums[0::2], hexnums[1::2]): 
            digit = '0' if num2 // num1 == 3 else '1' 
            outfile.write(digit) 
        outfile.write('\n') 

我得到 768 行输出,就像输入一样,第一行是:

01000000000000010100011111111111 
01000100000000010100001111111111 
01000010000000010100010111111111 
01000110000000010100000111111111 
01000001000000010100011011111111 
01000101000000010100001011111111 
01000011000000010100010011111111 
01000111000000010100000011111111 
01000000100000010100011101111111 
01000100100000010100001101111111 
01000010100000010100010101111111 
01000110100000010100000101111111 
01000001100000010100011001111111 
01000101100000010100001001111111 
01000011100000010100010001111111 
01000111100000010100000001111111 
01000000010000010100011110111111 
01000100010000010100001110111111 
01000010010000010100010110111111 
01000110010000010100000110111111