如何在文本文件中单独拆分python中的数字?

时间:2017-01-08 01:38:26

标签: python python-2.7

这个问题在其他方面有些相同,但我试图解释的不同,因为我也是python的新手。

假设我有sample.txt:

123
456

321
780

两者都被空白区分开。但我希望它们看起来像:

>> goal = '123456'
>> start = '456312'

我的启动代码看起来像:

with open('input.txt') as f:
    out = f.read().split()
    print map(int, out)

导致:

>> [123, 456, 456, 123]

这与我试图施加的不同。

2 个答案:

答案 0 :(得分:3)

您可以做的一件事是逐行遍历文件,如果该行为空,则在结果列表中开始一个新字符串,否则将该行附加到结果列表的最后一个元素:

lst = ['']

with open('input.txt', 'r') as file:

    for line in file:
        line = line.rstrip()
        if len(line) == 0:
            lst.append('')
        else:
            lst[-1] += line

lst
# ['123456', '321780']

答案 1 :(得分:-1)

Splint on \ n \ n。 (如果这不是您所需要的,那么请修改以适应!)

>>> inp = '123\n456\n\n321\n780\n'
>>> [int(num.replace('\n', '')) for num in inp.split('\n\n')]
[123456, 321780]