从格式化多行输出文件创建列表

时间:2016-02-10 23:12:02

标签: python

我正在尝试处理TEXT文件,我正在读取文件并尝试从多行创建列表。

with open(filename1, 'r') as file1:
        for line in file1:
            strings2 = []
            strings1 = line.rsplit(': ', 1)[1]
            print ("Text 1 output is: {}".format(strings1))
            strings2 = strings1.split(',')
    print ("output-1 is:{}".format(strings3))

FILE.TXT:

12345: apple is fruit
34354: grapes is also fruit

预期输出:

[apple is fruit, grapes is also fruit]

实际输出:

[grapes is also fruit]

3 个答案:

答案 0 :(得分:0)

if (photo_array.jsonError !== undefined) {
    alert('An error occurred: ' + photo_array.jsonError);
    return;
}

假设您可以保证文件格式,那就没问题了。这假定第一个空格之前的任何内容都未使用。如果你想用冒号(即with open(filename1, 'r') as file1: lines = [' '.join(line.split(" ")[1:]).rstrip() for line in file1] 没有空格)将它拆分,那么你可以这样做:

1234:testing 123

答案 1 :(得分:0)

这应该可以帮到你

>>> with open(filename) as f:
...  lst = [line.rstrip('\n').split(': ')[1] for line in f]
... 
>>> lst
['apple is fruit', 'grapes is also fruit']

答案 2 :(得分:0)

也许将strings2初始化移到for循环之外并使用append?例如:

with open(filename1, 'r') as file1:
    strings2 = []
    for line in file1:
        strings1 = line.rsplit(': ', 1)[1].strip()
        print "Text 1 output is: {}".format(strings1)
        strings2.append(strings1)

print strings2