如何在python中读取文件字符串,并在读取分配给列表后

时间:2012-06-20 05:55:29

标签: python

例如: 创建文件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 ]

1 个答案:

答案 0 :(得分: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 ]