-4

比如:创建一个文件bit0.txt 里面的文件内容是:

Port   Command        ExpectedResult           Comments

A        C            Ack Resp:\x43\x80   ;  All flags bit of port A clear
B        C            Ack Resp:\x43\x80   ;  All flags bit of port B clear
A     S001002         Ack Resp:\x06\x53   ;  S command Change output 1
A        C            Ack Resp:\x43\x81   ;  port A bit 0 set
B        C            Ack Resp:\x43\x81   ;  port B bit 0 set
A        Q            Ack Resp:\x51\x31   ;  read change queue on port A
A        C            Ack Resp:\x43\x80   ;  port A bit 0 clear
B        C            Ack Resp:\x43\x81   ;  port B bit 0 set
B        Q            Ack Resp:\x51\x31   ;  read change queue on port B
A        C            Ack Resp:\x43\x80   ;  port A bit 0 clear
B        C            Ack Resp:\x43\x80   ;  port B bit 0 clear

现在我必须通过另一个 python 程序读取这个文件,输出应该是这样的:

读取文件后,API 应返回:

result = [['A','C', 'Ack Resp:\x43\x80'],
          ['B','C', 'Ack Resp:\x43\x80'],
          ['A','S001002', 'Ack Resp:\x06\x53'],
          ...............till end of file ]
4

1 回答 1

0

您可以import csv或自己编写代码。有一个例子:

result = []
with open(bit0.txt) as f:
    for index, l in enumerate(f):
        if index > 1:
            result.append((l.split(';')[0]).split())

result论据是你想要的

或者可以function这样定义:

def helper(filename):
    result = []
    with open(filename) as f:
        for index, l in enumerate(f):
            if index > 1:
                result.append((l.split(';')[0]).split())
    return result

print helper(bit0.txt)

输出是

[['A','C', 'Ack Resp:\x43\x80'],
      ['B','C', 'Ack Resp:\x43\x80'],
      ['A','S001002', 'Ack Resp:\x06\x53'],
      ...............till end of file ]
于 2012-06-20T06:13:30.657 回答