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']]
添加回答
舉報