Question

I have a text file that I would like to pass to python and create a tuple every time a new space comes up a new tuple is created.

Lets say for example I have the following file

land, 3
-4,-2
4,3

ocean, 5
3,4
-6,5
5,6

my aim is to create a tuple for the first one, then when we hit the space another tuple is created for the second and so on until we get to the last.

Was it helpful?

Solution

Not the most elegant solution. The wanted output is quite strange.

fp = open('test.txt', 'r')
file_contents = fp.read()
result = []
for split in file_contents.split('\n\n'):
    split = ','.join(split.split('\n'))
    split = ''.join(split.split(' '))
    split = split.split(',')
    for x in range(0, len(split)-1, 2):
        if x == 0:
            result.append(split[x])
            result.append((0, int(split[x+1])))
        else:
            result.append((int(split[x]), int(split[x+1])))
print result

Produces:

['land', (0, 3), (-4, -2), (4, 3), 'ocean', (0, 5), (3, 4), (-6, 5), (5, 6)]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top