逐行将文本文件读入多个列表

时间:2017-01-13 08:50:01

标签: python string text readline

如果我们有一个文本文件如下:

6   &   ロク3 &   サン
9   &   キュウ
0   &   ゼロ5 &   ゴ
7   &   ナナみぎ    &   ミギひだり   &   ヒダリ
うえ  &   ウエ

如何将其读入python以获取每个“列”的列表,如下所示:

a = ["6", "9", "0", "7", "うえ"]
b = ["ロク3" , "キュウ", "ゼロ5", "ナナみぎ", "ウエ"]
c = ["サン", "", "ゴ}", "ミギひだり", ""]
d = ["", "ヒダリ", "", "", ""]

2 个答案:

答案 0 :(得分:1)

试试这个:

with open(path, 'r') as inputFile:
    lines = list()

    for line in inputFile:
        lines.append(line.split("&"))

    maxLen = len(max(lines, key=lambda x: len(x)))

    for line in lines:
        while len(line) < maxLen:
            line.append(" ")

    column0 = [line[0] for line in lines]
    column1 = [line[1] for line in lines]
    .
    .
    .

此外,如果您想删除“单元格”中的空格,请使用replace方法:

without_spaces = with_spaces.replace(" ", "")

要使用它,只需替换

lines.append(line.split("&"))

lines.append(line.replace(" ", "").split("&"))

答案 1 :(得分:1)

itertools.izip_longest对任务来说非常方便。

import itertools

def cleanup(alist):
    return [item.strip() for item in alist]

with open('input.txt', 'r') as input_file:
    lines = input_file.readlines()
    contents = [cleanup(line.split('&')) for line in lines]
    zipped = itertools.izip_longest(*contents, fillvalue='')

    for column in zipped:
        print column

请注意,zipped实际上是所有列的迭代器。