如何将文本板中的所有行显示到列表中。Python3错误

如何将文本板中的所有行显示到列表中。Python3错误,python,list,python-3.x,Python,List,Python 3.x,我想要实现的是尝试用文本打开一个文本文件。文本的格式如下所示: Bear Car Plant 等等。现在我有了代码: try: with open(info) as information: for line in information.readlines(): line = line.split() except IOError as error: print("Failed to open. Try again.") 仅打印列表中

我想要实现的是尝试用文本打开一个文本文件。文本的格式如下所示:

Bear
Car
Plant
等等。现在我有了代码:

try:
    with open(info) as information:
        for line in information.readlines():
            line = line.split()
except IOError as error:
    print("Failed to open. Try again.")
仅打印列表中的最后一行。我要做的是打印出列表中的所有单词

因此,对于上面的示例,当我打印(行)时,它打印
['Plant']
,但我想要
['Bear'、'Car'、'Plant']


谁能把我引向正确的方向

您不需要拆分,您需要使用剥离(删除换行符),然后将结果添加到列表中:

lines = []
with open(info) as information:
    for line in information:
        lines.append(line.strip())
请注意,根本不需要调用
file.readlines()
;只需迭代文件就足够了

您可以通过读取整个文件并使用以下命令一次性完成此操作:

或者您也可以在列表中使用迭代:

with open(info) as information:
    lines = [line.strip() for line in information]

readlines
将文件作为列表读取

try:
    with open(info) as information:
        lines =  information.readlines()
except IOError as error:
    print("Failed to open. Try again.")
您还可以使用
列表

try:
    with open(info) as information:
        lines = list(information)
except IOError as error:
    print("Failed to open. Try again.")
try:
    with open(info) as information:
        lines = list(information)
except IOError as error:
    print("Failed to open. Try again.")