簡體   English   中英

如何逐行讀取文本文件並從文件內容中返回兩個字符串和一個列表?

[英]How do I read a text file line by line and return two strings and a list from the contents of the file?

因為我想同時將文本文件讀入字符串和列表,所以我對如何 go 感到困惑。 我正在嘗試使用 for 循環和設置條件,但我仍然不確定。 文本文件內容為:

2018 年最高進球者

國家

澳大利亞,529

牙買加,466

英格蘭,450

新西蘭,391

南非,363

我正在嘗試返回 output ,看起來像這樣:

“2018 年最高進球者”,

'國家'

['澳大利亞,529\n','牙買加,466\n','英格蘭,450\n','新西蘭,391\n','南非,363']

嘗試這個:

with open('file.txt') as f:
    content = [line for line in f.readlines() if line != '\n']
    first_line = content[0].rstrip('\n')
    second_line = content[1].rstrip('\n')
    other_lines = [line for line in content[2:]]

嘗試這個:

with open('text.txt') as f:
    lines =f.read()
    lines_list = [line for line in lines.split('\n') if line]
    print(lines_list[2:])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM