[英]Python- Creating a tuple from a txt file
我目前正在尝试从文本文件中取出信息并将其存储在一个元组中。 所以目前文本文件如下所示:
name age height weight
name age height weight
等等
我想将它们取出并存储在单独的元组中,例如名称元组、年龄元组、高度元组。 但我收到“ ValueError: too many values to unpack (expected 4)
”
我知道如何使用我现在拥有的代码将其放入列表中
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()])
需要一些帮助谢谢大家
我使用 python 3.4
您可以像这样使用zip
和理解
text_file = open("Input.txt", "r")
name, age, height, weight = zip(*[l.split() for l in text_file.readlines()])
它总是很好用with
,当你正在处理的文件
with open("Input.txt", "r") as text_file:
name, age, height, weight = zip(*[l.split() for l in text_file.readlines()])
示例运行:
~/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.