Yanis Boucherit
Yanis Boucherit

Reputation: 714

Generate special list from file in python

I have a file like this :

one:two:three
four:five:six
seven:height:nine

And so on... What I want is to parse it correctly to obtain this kind of variable:

myVar = [("one", "two", "three"), ("four", "five", "six"), ("seven", "height", "nine")]

Of course, the file isn't stopping at nine, there's a lot more of lines after that.

How can I do that in Python ?

Thanks !

Upvotes: 0

Views: 51

Answers (3)

vaultah
vaultah

Reputation: 46533

with open('your file') as f:
    myVar = [ tuple(a.split(':')) for a in f.read().split() ]

print myVar

Outputs

[('one', 'two', 'three'), ('four', 'five', 'six'), ('seven', 'height', 'nine')]

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 239473

The data you are dealing with, looks like delimiter separated. I would recommend using csv.reader, like this

import csv
with open("Input.txt") as in_file:
    reader = csv.reader(in_file, delimiter=':')
    print [row for row in reader]

You can convert this to a tuple, like this

    print [tuple(row) for row in reader]

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

Use a list compehension:

with open('filename') as f:
    myVar = [line.rstrip().split(':') for line in f]

If you need a list to tuples then pass line.rstrip().split(':') to tuple():

tuple(line.rstrip().split(':'))

Upvotes: 2

Related Questions