[英]Forming a tuple/list from a text file in Python
I have file of format: 我有以下格式的文件:
C1 A1
C2 A2
C3 A3
C1 A4
C4 A5
Each line is separted by a tab. 每行由一个标签分隔。 Can I get this file in array/list/tuple directly so that the columns of each line can be accessible through index?
我可以直接在array / list / tuple中获取此文件,以便可以通过索引访问每一行的列吗? Like [(c1,a1),(c2,a2)..] Any python functions allows us to do this?
像[(c1,a1),(c2,a2)..]一样,任何python函数都允许我们执行此操作?
This should do : 应该这样做:
with open('filename.txt') as file:
result = [line.split() for line in file]
It outputs : 输出:
>>> with open('filename.txt') as file:
... result = [line.split() for line in file]
...
>>> result
[['C1', 'A1'], ['C2', 'A2'], ['C3', 'A3'], ['C1', 'A4'], ['C4', 'A5']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.