[英]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.