【问题标题】:How do I read a text file line by line and return two strings and a list from the contents of the file?如何逐行读取文本文件并从文件内容中返回两个字符串和一个列表?
【发布时间】:2022-01-03 19:12:08
【问题描述】:
因为我想同时将文本文件读入字符串和列表,所以我不知道如何去做。我正在尝试使用 for 循环和设置条件,但我仍然不确定。文本文件内容为:
2018 年进球最多的球员
国家
澳大利亚,529
牙买加,466
英格兰,450
新西兰,391
南非,363
我正在尝试返回并输出如下所示:
“2018 年最高进球者”,
“国家”
['澳大利亚,529\n','牙买加,466\n','英格兰,450\n','新西兰,391\n','南非,363']
【问题讨论】:
标签:
python
string
list
file
text
【解决方案1】:
试试这个:
with open('text.txt') as f:
lines =f.read()
lines_list = [line for line in lines.split('\n') if line]
print(lines_list[2:])
【解决方案2】:
试试这个:
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:]]