python 读取txt文件到列表中

2025-03-21 22:13:31
推荐回答(3个)
回答1:

#-*- 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。

回答2:

请看代码:

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

回答3:

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