2015-09-16 100 views
2

我正在使用此代码将文本文件读取到列表中。将txt文件读入列表Python

with open("products.txt", "r") as f: 
    test=f.read().splitlines() 

print(test) 

产生的输出是:

['88888888,apple,0.50', '99999999,pear,0.20', '90673412,orange,1.20'] 

我需要的输出看起来像下面这样我可以参考的单个元素。

['88888888', 'apple', '0.50', '99999999', 'pear', '0.20', '90673412', 'orange', '1.20'] 
+0

它看起来像你正在阅读的CSV数据。你可以使用[csv](https://docs.python.org/2/library/csv.html)模块。 –

+0

你有一个CSV文件,而不仅仅是一个文本看看库解析这些 – Mark

+0

什么是输入文件的样子? – erip

回答

1

您可以使用嵌套列表理解:

with open("products.txt", "r") as f: 
    test=[i for line in f for i in line.split(',')] 

或者使用csv模块拒绝分割线:

>>> import csv 
>>> with open('products.txt') as csvfile: 
...  spamreader = csv.reader(csvfile, delimiter=',') 
     test=[i for row in spamreader for i in row]