用Python将文件读入多维数组

用Python将文件读入多维数组,python,multidimensional-array,Python,Multidimensional Array,如果我有这样一个文本文件: Hello World How are you? Bye World [["Hello", "World"], ["How", "are", "you?"], ["Bye" "World"]] 我如何将其读入如下多维数组: Hello World How are you? Bye World [["Hello", "World"], ["How", "are", "you?"], ["Bye" "World"]] 我试过: textFile = ope

如果我有这样一个文本文件:

Hello World
How are you?
Bye World
[["Hello", "World"],
 ["How", "are", "you?"],
 ["Bye" "World"]]
我如何将其读入如下多维数组:

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

如何将文件读入多维数组?

使用列表理解和
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']]
:

处理文件时,最好将
关键字一起使用 物体。这样做的好处是,文件在关闭后会正确关闭 它的套件完成了,即使在途中出现了异常。它是 也比编写等效try finally块短得多


另外,不要忘记使用
条带
删除
\n

myArray = []
textFile = open("textFile.txt")
lines = textFile.readlines()
for line in lines:
    myArray.append(line.split(" "))
您可以与unbound方法一起使用:


在Python3.x中,必须使用
list(map(str.split,…)
来获取列表,因为在Python3.x中,返回的是迭代器而不是列表。

添加到接受的答案中:

with open("textFile.txt") as textFile:
    lines = [line.strip().split() for line in textFile]

如果将“\n”附加到每行末尾,则会将其删除。

一个好的答案是:

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

lines=map(str.split,open('testFile.txt'))
@falsetru。我想这是最快的。发布答案。@GrijeshChauhan
str.split()
不带参数会处理所有类型的空白字符。它应该是
map(lambda行:line.split,open('testFile.txt'))
,当我执行
str.splite
时,它会说str not object。@GrijeshChauhan,你不需要
lambda
,因为
str.split
是未绑定的方法
'abc'.split()
类似于
str.split('abc')
@GrijeshChauhan,
str.splite
?是打字错误吗?或者,您是否覆盖了
str