在 Python 中读取文件并打印出来

我是python的新手。我想读一个文件。文件中的内容是:


17 2 3 0


5 16 11 7


9 8 0 6


0 14 17 1

我想像这样阅读并打印出来:


aList= [[17,2,3,0],

        [5,16,11,7],

        [9,8,0,6],

        [0,14,17,1]]   

这是我的代码:


file = open("file.txt","r")

aList=[]

for line in file:

aList.append(line.strip().split(",")) 

现在错误是找不到文件,无法打印出来。


哆啦的时光机
浏览 373回答 3
3回答

慕姐8265434

试试这个:aList = []with open('file.txt') as handle:    for text in handle:        aList.append(text.strip().split())print(list(filter(None, aList)))输出是: [['17', '2', '3', '0'], ['5', '16', '11', '7'], ['9', '8', '0', '6'], ['0', '14', '17', '1']]

莫回无

更短:with open(filname,'r') as f:   print([line.split() for line in f if line.split()])

慕码人8056858

希望这有帮助:    flread=open('path/to/file/filename','r')    for i in flread.readlines():        for k in i.split(' '):             a.append(int(k))             a=[]        b.append(a)     print(b)输出: [[17, 2, 3, 0], [5, 16, 11, 7], [9, 8, 0, 6], [0, 14, 17, 1]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python