Skip to main content
 首页 » 编程设计

python之将txt文件读入列表Python

2025年05月04日21lidabo

我正在使用这段代码将文本文件读入列表。

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'] 

请您参考如下方法:

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

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]