[英]How do I read a text file line by line and return two strings and a list from the contents of the file?
Because I want to read the text file into strings and a list at the same time, I'm stuck as to how to go about it.因为我想同时将文本文件读入字符串和列表,所以我对如何 go 感到困惑。 I'm trying using for loops and setting conditions but I'm still not sure.
我正在尝试使用 for 循环和设置条件,但我仍然不确定。 The text file content is:
文本文件内容为:
Highest Goal Scorers 2018 2018 年最高进球者
Country国家
Australia, 529澳大利亚,529
Jamaica, 466牙买加,466
England, 450英格兰,450
New Zealand, 391新西兰,391
South Africa, 363南非,363
And I'm trying to return and output that looks like this:我正在尝试返回 output ,看起来像这样:
'Highest Goal Scorers 2018', “2018 年最高进球者”,
'Country' '国家'
['Australia, 529\n', 'Jamaica, 466\n', 'England, 450\n', 'New Zealand, 391\n', 'South Africa, 363'] ['澳大利亚,529\n','牙买加,466\n','英格兰,450\n','新西兰,391\n','南非,363']
Try this:尝试这个:
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:]]
try this:尝试这个:
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.