python 读取txt文件到列表中

假如txt文件内容为:aaa,bbb,ccc
ddd,eee,fff

我要读取保存到列表中去,显示结果为[[aaa,bbb,ccc],
[ddd,eee,fff]]

该怎么写

#-*- coding:utf-8 -*-

f = open('123.txt', 'r')              #文件为123.txt
sourceInLines = f.readlines()  #按行读出文件内容
f.close()
new = []                                   #定义一个空列表,用来存储结果
for line in sourceInLines:
    temp1 = line.strip('\n')       #去掉每行最后的换行符'\n'
    temp2 = temp1.split(',')     #以','为标志,将每行分割成列表
    new.append(temp2)          #将上一步得到的列表添加到new中
    
print new

最后输出结果是:[['aaa', 'bbb', 'ccc'], ['ddd', 'eee', 'fff']],注意列表里存的是字符串'aaa',不是变量名aaa。

追问

你的也行,不过先采纳了第一个,谢谢你了

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-06-09

请看代码:

txtpath=r"a.txt"
fp=open(txtpath)
arr=[]
for lines in fp.readlines():
    lines=lines.replace("\n","").split(",")
    arr.append(arr)
fp.close()

本回答被提问者采纳
第2个回答  2018-02-12
#Python3
fp=open("a.txt",“r”)
arr=[]
for lines in fp.readlines():
lines=lines.replace("\n","").split(",")
arr.append(lines)
print(arr)
fp.close()