我想用python读取文件 结果必须像(元组列表):
myList=[(1, 'assignment_1', 85,100', '0.05'),
('2', 'assignment_2', '80', '100', '0.05'),
('3', 'assignment_3', '95', '100', '0.05')]
该文件包含:
1 assignment_1 85 100 0.05
2 assignment_2 80 100 0.05
3 assignment_3 95 100 0.05
我的代码:
inputfile=open(filename,"r")
myList=[]
for line in inputfile.readlines():
tuples=line.split()
myList.append(tuples)
print(myList)
fileinput.close()
结果
[['1', 'assignment_1', '85', '100', '0.05'],
['2', 'assignment_2', '80', '100', '0.05'],
['3', 'assignment_3', '95', '100', '0.05']]
如何将项目转换为每种类型(int
,float
)。我得到了一个列表列表,而不是元组列表
答案 0 :(得分:2)
您可以在读取它们之后立即将元素转换为正确的类型:
from pprint import pprint
types = int, str, int, int, float
filename = 'assignments.txt'
with open(filename, "r") as inputfile:
myList = []
for line in inputfile:
elements = tuple(t(e) for t,e in zip(types, line.split()))
myList.append(elements)
pprint(myList)
输出:
[(1, 'assignment_1', 85, 100, 0.05),
(2, 'assignment_2', 80, 100, 0.05),
(3, 'assignment_3', 95, 100, 0.05)]
可以更简洁地完成此操作
with open(filename, "r") as inputfile:
myList = [tuple(t(e) for t,e in zip(types, line.split()))
for line in inputfile]
另请注意,您不需要使用readlines()
一次将file
的所有行读入内存,因为文件可以逐行进行迭代。这在Python的在线文档中的Tutorial中有所描述。
答案 1 :(得分:0)
添加到wpercy的答案,我认为实现这一目标的最简单方法如下:
with open(filename, 'r') as input_file:
my_list = [tuple(line.split()) for line in input_file]
答案 2 :(得分:0)
您可以使用以下内容:
myList = []
with open("text_to_tuple.txt") as f:
for line in f:
myList.append(tuple(line.rstrip().split())) # rstrip() removes line breaks
print(myList)
# [('1', 'assignment_1', '85', '100', '0.05'), ('2', 'assignment_2', '80', '100', '0.05'), ('3', 'assignment_3', '95', '100', '0.05')]