如果我有这样的文本文件:
Hello World
How are you?
Bye World
我如何将其读入如下的多维数组:
[["Hello", "World"],
["How", "are", "you?"],
["Bye" "World"]]
我试过了:
textFile = open("textFile.txt")
lines = textFile.readlines()
for line in lines:
line = lines.split(" ")
但它只会返回:
["Hello World\n", "How are you?\n", "Bye World"]
如何将文件读入多维数组?
答案 0 :(得分:12)
使用列表推导和str.split
:
with open("textFile.txt") as textFile:
lines = [line.split() for line in textFile]
<强>演示:强>
>>> with open("textFile.txt") as textFile:
lines = [line.split() for line in textFile]
...
>>> lines
[['Hello', 'World'], ['How', 'are', 'you?'], ['Bye', 'World']]
在处理文件时,最好使用
with
关键字 对象。这样做的好处是文件在之后正确关闭 即使在途中出现异常,它的套件也会完成。它是 也比编写等效的try-finally块短得多。
答案 1 :(得分:3)
>>> map(str.split, open('testFile.txt'))
[['Hello', 'World'], ['How', 'are', 'you?'], ['Bye', 'World']]
在Python 3.x中,您必须使用list(map(str.split, ...))
来获取列表,因为Python 3.x中的map
返回迭代器而不是列表。
答案 2 :(得分:0)
另请不要忘记使用strip
删除\n
:
myArray = []
textFile = open("textFile.txt")
lines = textFile.readlines()
for line in lines:
myArray.append(line.split(" "))
答案 3 :(得分:0)
添加到接受的答案:
with open("textFile.txt") as textFile:
lines = [line.strip().split() for line in textFile]
这将删除&#39; \ n&#39;如果它被附加到每一行的末尾。
答案 4 :(得分:0)
一个好的答案是:
def read_text(path):
with open(path, 'r') as file:
line_array = file.read().splitlines()
cell_array = []
for line in line_array:
cell_array.append(line.split())
print(cell_array)
针对可读性进行了优化。
但是python语法让我们使用更少的代码:
def read_text(path):
with open(path, 'r') as file:
line_array = file.read().splitlines()
cell_array = [line.split() for line in line_array]
print(cell_array)
而且python让我们只在一行中做到这一点!!
def read_text(path):
print([[item for item in line.split()] for line in open(path)])