Reputation: 287
This question is somewhat the same about others but different on what I'm trying to interpret as i'm also new to python.
suppose that i have sample.txt:
123
456
321
780
both are separated by white space. but i wanted them to look like:
>> goal = '123456'
>> start = '456312'
and my start up code somehow looks like:
with open('input.txt') as f:
out = f.read().split()
print map(int, out)
which results to:
>> [123, 456, 456, 123]
which is different from what I''m trying to exert.
Upvotes: 1
Views: 1959
Reputation: 1114
Splint on \n\n. (If this isn't exactly what you need, then modify to suit!)
>>> inp = '123\n456\n\n321\n780\n'
>>> [int(num.replace('\n', '')) for num in inp.split('\n\n')]
[123456, 321780]
Upvotes: -1
Reputation: 215107
One thing you can do is loop through the file line by line, and if the line is empty then start a new string in the result list, otherwise append the line to the last element of the result list:
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']
Upvotes: 3