将 txt 文件读入列表 Python

Read txt file into list 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']

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

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]