读取文件并用Python打印出来

时间:2018-09-04 04:44:32

标签: 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(",")) 

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

4 个答案:

答案 0 :(得分:1)

尝试一下:

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']]

答案 1 :(得分:1)

更短:

<action name="/*" class="org.apache.struts.webapp.example.ErrorAction">
    <result>error.jsp</result>
</action>

答案 2 :(得分:0)

希望获得帮助:

    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]]

答案 3 :(得分:-1)

文件路径将相对于您的 python脚本(.py文件)当前工作目录采用。您需要将file.txt .py文件 cwd放在同一目录中,或者将file.txt的绝对路径用于open()函数例如open('/path/to/your/file.txt')(假设您正在运行Linux)或open('C:\\path\\to\\your\\file.txt')(Windows)。