user3077551
user3077551

Reputation: 79

Python- Creating a tuple from a txt file

I am currently trying to take out information from a text file and store it in a tuple. So at the moment the text file looks like this:

name age height weight
name age height weight

and so on

I want to take them out and store them in separate tuples, such as name tuple, age tuple, height tuple. But I am getting "ValueError: too many values to unpack (expected 4)"

I know how to get it in a list with the code I have now

file1 = open(input (str("Please enter the name of the file you wish to open:" )),"r")
name, age, height, weight = zip(*[l.split() for l in file1.readlines()])

need some help thanks guys

im using python 3.4

Upvotes: 0

Views: 4547

Answers (1)

thefourtheye
thefourtheye

Reputation: 239493

You can use zip and comprehension like this

text_file = open("Input.txt", "r")
name, age, height, weight = zip(*[l.split() for l in text_file.readlines()])

Its always good to use with, when you are dealing with files

with open("Input.txt", "r") as text_file:
    name, age, height, weight = zip(*[l.split() for l in text_file.readlines()])

Sample Run:

~/Desktop$ python3 Test.py
Please enter the name of the file you wish to open:Input.txt
('alex',) ('17',) ('170',) ('6.4',)
~/Desktop$ 

Upvotes: 4

Related Questions