使用 Python 将文件读入多维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19056125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading a file into a multidimensional array with Python
提问by LazySloth13
If I have a text file like this:
如果我有这样的文本文件:
Hello World
How are you?
Bye World
How would I read it into a multidimensional array like this:
我如何将它读入这样的多维数组:
[["Hello", "World"],
["How", "are", "you?"],
["Bye" "World"]]
I have tried:
我试过了:
textFile = open("textFile.txt")
lines = textFile.readlines()
for line in lines:
line = lines.split(" ")
But it just returns:
但它只是返回:
["Hello World\n", "How are you?\n", "Bye World"]
How do I read the file into a multidimensional array?
如何将文件读入多维数组?
采纳答案by Ashwini Chaudhary
Use a list comprehension and str.split
:
使用列表理解和str.split
:
with open("textFile.txt") as textFile:
lines = [line.split() for line in textFile]
Demo:
演示:
>>> with open("textFile.txt") as textFile:
lines = [line.split() for line in textFile]
...
>>> lines
[['Hello', 'World'], ['How', 'are', 'you?'], ['Bye', 'World']]
It is good practice to use the
with
keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks.
with
在处理文件对象时使用关键字是一种很好的做法。这样做的好处是文件在其套件完成后会被正确关闭,即使在途中引发异常也是如此。它也比编写等效的 try-finally 块要短得多。
回答by Nacib Neme
Also don't forget to use strip
to remove the \n
:
也不要忘记使用strip
删除\n
:
myArray = []
textFile = open("textFile.txt")
lines = textFile.readlines()
for line in lines:
myArray.append(line.split(" "))
回答by falsetru
You can use map
with the unbound methodstr.split
:
>>> map(str.split, open('testFile.txt'))
[['Hello', 'World'], ['How', 'are', 'you?'], ['Bye', 'World']]
In Python 3.x, you have to use list(map(str.split, ...))
to get a list because map
in Python 3.x return an iterator instead of a list.
在 Python 3.x 中,您必须使用list(map(str.split, ...))
来获取列表,因为map
在 Python 3.x 中返回的是迭代器而不是列表。
回答by Shaahiin
Adding to the accepted answer:
添加到接受的答案:
with open("textFile.txt") as textFile:
lines = [line.strip().split() for line in textFile]
This will remove '\n' if it is appended to the end of each line.
如果将 '\n' 附加到每行的末尾,这将删除它。
回答by AmiNadimi
A good answer would be :
一个好的答案是:
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)
Which is optimized for readability.
这是为了可读性而优化的。
But python syntax let's us use less code:
但是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)
And also python let's us do it only in one line!!
还有python让我们只在一行中完成!!
def read_text(path):
print([[item for item in line.split()] for line in open(path)])