首页 > 解决方案 > 使用python在列中返回值而不是按行从文件中打印行

问题描述

我一定忘记了基本的python,因为在拆分它们之后我似乎无法按实际行打印行,以便每行都作为列表中的元素。

例如:

for lines in open(testfile):
     print(lines.split())

输出(注意这不是列表的列表):

 ["The", "apple", "banana", "check"]
 ["Two", "apples", "three", "checks", "testest"]
 ["This", "is", "a", "test", "file"]

因此,如果我想自己打印第一行,我将代码更改为:

for lines in open(testfile):
     print(lines.split()[0])

但是我得到了每个行列表中的第一个元素:

 "The"
 "Two"
 "This"

但我期望:

["The", "apple", "banana", "check"]

我知道这是语法错误,我已经查过了,但我一直只得到第一个元素。抱歉,这太基础了,但我已经有一段时间没有做这样简单的事情了!

标签: python

解决方案


您的for循环将依次查看每一行,因此当您print(lines.split()[0])执行此操作时,您一次只针对一行。您可以做的是将所有拆分的行放在自己的列表中,然后查看列表中的第一个元素:

all_lines = []  # empty list
for line in open(testfile):
     all_lines.append(line.split())
all_lines[0]
# ["The", "apple", "banana", "check"]

顺便说一句,打开文件时最好使用以下with语句:

all_lines = []
with open(testfile) as a_file:
    for line in a_file:
        all_lines.append(line.split())

这里的优点是它创建了一个运行文件操作的上下文,并自动处理诸如关闭文件之类的事情。

最后,如果你只关心文件的第一行,你可以这样做:

with open(testfile) as a_file:
    first_line = a_file.readline().split()  # grab just the first line
first_line
# ["The", "apple", "banana", "check"]

推荐阅读