0

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 !

3 Answers 3

2

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(':'))
Sign up to request clarification or add additional context in comments.

1 Comment

Worked great thanks ! I was going waaay to complicated for this. Python is such a great language.
2

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]

Comments

2
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')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.