使用Python将文件读取到多维数组 [英] Reading a file into a multidimensional array with Python

查看:542
本文介绍了使用Python将文件读取到多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的文本文件:

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

我尝试过:

textFile = open("textFile.txt")
lines = textFile.readlines()
for line in lines:
    line = lines.split(" ")

但它只会返回:

["Hello World\n", "How are you?\n", "Bye World"]

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

How do I read the file into a multidimensional array?

推荐答案

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

优良作法是在处理文件时使用with关键字 对象.这样做的好处是,文件在关闭后会正确关闭 即使在途中引发异常,其套件也会完成.它是 也比编写等效的try-finally块要短得多.

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.

这篇关于使用Python将文件读取到多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆