>我有这样的文件:
one:two:three
four:five:six
seven:height:nine
等等...我想要的是正确解析它以获得这种变量:
myVar = [("one", "two", "three"), ("four", "five", "six"), ("seven", "height", "nine")]
当然,文件不会停在九点,之后还有更多的行。
如何在 Python 中做到这一点?
谢谢!
使用列表理解:
with open('filename') as f:
myVar = [line.rstrip().split(':') for line in f]
如果您需要一个列表到元组,则将line.rstrip().split(':')
传递给tuple()
:
tuple(line.rstrip().split(':'))
您正在处理的数据看起来像分隔符。我建议使用csv.reader
,像这样
import csv
with open("Input.txt") as in_file:
reader = csv.reader(in_file, delimiter=':')
print [row for row in reader]
你可以把它转换成元组,像这样
print [tuple(row) for row in reader]
with open('your file') as f:
myVar = [ tuple(a.split(':')) for a in f.read().split() ]
print myVar
输出
[('one', 'two', 'three'), ('four', 'five', 'six'), ('seven', 'height', 'nine')]