Python读取txt并打印

时间:2016-05-04 03:35:42

标签: python python-2.7 python-3.x

http://i.stack.imgur.com/ZgthC.jpg

我只能读一张桌子。我需要有关如何在一个txt文件中读取大量表的帮助。 非常感谢你!

我的代码如下所示:

result=[]

with open('AAA.txt','r') as f:

for line in f:

  result.append(line.split('\t'))

print(result)

for line in result:

    if line[0]=="AAA":

     print(line[0]+" "+line[2]+" "+line[4])

2 个答案:

答案 0 :(得分:0)

下面是根据您指定的图像打印表格的示例代码。

<强> CODE

with open('table.txt', 'r') as table:
    while True:
        try:
            row1 = [i.strip() for i in table.readline().split('\t')] # Split based on number of spaces in btw 2 values or numbers
            row2 = [i.strip() for i in table.readline().split('\t')]
            print row1[0] + ' ' + row1[2] + ' ' + row1[4] + ' ' + row2[2] + ' ' + row2[4]
        except:
            break

文件(table.txt)

AAA BOOK    1   FOOD    1
    BOOK    3   FOOD    4
AAA BOOK    1   FOOD    1
    BOOK    3   FOOD    4
AAA BOOK    1   FOOD    1
    BOOK    3   FOOD    4
AAA BOOK    1   FOOD    1
    BOOK    3   FOOD    4
AAA BOOK    1   FOOD    1
    BOOK    3   FOOD    4

CONSOLE OUTPUT

enter image description here

答案 1 :(得分:0)

感谢您的回答!

我可以运行它。我的代码是这样的:

with open('AAA.txt', 'r') as table:
  while True:
    try:
        row1 = [i.strip() for i in table.readline().split('\t')] 
        row2 = [i.strip() for i in table.readline().split('\t')]
        row3 = [i.strip() for i in table.readline().split('\t')]
        print row1[0] + ' ' + row1[2] + ' ' + row1[4] + ' ' + row2[2] + ' ' + row2[4]
    except:
        break

我添加了row3,因为txt中有一个“enter”。

非常感谢你! ^^!