[英]Printing lines from file using python returning value in column, not by row
我一定忘记了基本的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"]
我知道这是语法错误,我已经查过了,但我一直只得到第一个元素。 抱歉,这太基础了,但我已经有一段时间没有做这样简单的事情了!
您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"]
您可以在打印第一行后立即break
:
for lines in open(testfile):
print(lines.split())
break
这将只打印第一行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.