2 回答
TA贡献1858条经验 获得超8个赞
使用csv模块:
import csv
with open('test.txt','rb') as myfile:
mylist = list(csv.reader(myfile, delimiter='|'))
即使没有模块,也可以直接拆分行,而无需始终将结果存储在中间列表中:
with open('test.txt','r') as myfile:
mylist = [line.strip().split('|') for line in myfile]
两种版本均导致:
>>> with open('test.txt','rb') as myfile:
... mylist = list(csv.reader(myfile, delimiter='|'))
...
>>> mylist
[['a', 'b', 'c', 'd'], ['a1', 'b1', 'c1', 'd1'], ['a2', 'b2', 'c2', 'd2'], ['a3', 'b3', 'c3', 'd3']]
>>> with open('test.txt','r') as myfile:
... mylist = [line.strip().split('|') for line in myfile]
...
>>> mylist
[['a', 'b', 'c', 'd'], ['a1', 'b1', 'c1', 'd1'], ['a2', 'b2', 'c2', 'd2'], ['a3', 'b3', 'c3', 'd3']]
TA贡献1798条经验 获得超3个赞
您可以str.split在list comprehension此处使用和。
with open(test.txt) as f:
lis = [line.strip().split('|') for line in f]
print lis
输出:
[['a', 'b', 'c', 'd'], ['a1', 'b1', 'c1', 'd1'], ['a2', 'b2', 'c2', 'd2'], ['a3', 'b3', 'c3', 'd3']]
添加回答
举报