简体   繁体   English

Python-从 txt 文件创建元组

[英]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) "但我收到“ 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我使用 python 3.4

You can use zip and comprehension like this您可以像这样使用zip和理解

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 ,当你正在处理的文件

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$ 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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