我正在学习 python 编程并且被这个问题所困扰。我查看了其他示例,这些示例读取文件输入并将整个内容作为单个列表或字符串 link to that example 但我希望每一行都是一个列表(嵌套列表)我该怎么做请帮忙
文本文件为a.txt
1234 456 789 10 11 12 13
4456 585 568 2 11 13 15
代码的输出应该是这样的
[ [1234 456 789 10 11 12 13],[4456 585 568 2 11 13 15] ]
最佳答案
没有理由执行 readlines
-- 只是遍历文件。
with open('path/to/file.txt') as f:
result = [line.split() for line in f]
如果你想要一个整数列表的列表:
with open('path/to/file.txt') as f:
result = [map(int, line.split()) for line in f]
# [list(map(int, line.split())) for line in f] in Python3
关于python - 如何将文件的内容写入python中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28372562/