繁体   English   中英

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

[英]Read File and Print It Out in 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(",")) 

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

尝试这个:

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

希望这有帮助:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM