简体   繁体   中英

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

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$ 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM