读取文件并用Python打印出来
我是python新手。 我想读一个文件。文件中的内容包括:读取文件并用Python打印出来,python,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.s
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(","))
现在错误是找不到文件,无法将其打印出来 试试这个:
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()])
文件路径将相对于当前工作目录中的python script.py文件。您需要将file.txt保存在与.py文件cwd相同的目录中,或者使用file.txt的绝对路径作为打开函数,例如open'/path/to/your/file.txt',假设您正在运行Linux或open'C:\\path\\to\\your\\file.txt'窗口。希望这对您有所帮助:
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]检查文件路径。我想将其打印为整数怎么样?aList.append[inti for I in text.strip.split]在我的答案中使用此选项而不是aList.appendtext.strip.split。这将使您获得IntegerOK,而不是您的帮助。文件路径是相对于当前工作目录的,而不是相对于script@brunodesthuilliers对不起,我不知道。更新了我的帖子。