简体   繁体   English

如何逐行读取文本文件并从文件内容中返回两个字符串和一个列表?

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

相关问题 如何返回从文本文件中读取的行号? - How to return the line number of a line being read from a text file? 如何检查两个字符串是否在文件的同一行上? - How do i check if two strings are on the same line in a file? Google App Engine:如何将上传的文本文件保存到Blob,然后逐行读取? - Google App Engine: How do I save uploaded text file to Blob, then read from it line by line? 如何在文本文件中搜索行的内容,替换行并另存为新文件? - How do I search for contents of a line in a text file, replace the line, and save as a new file? 从python第二行读取文本文件内容 - Read a text file contents from second line in python 如何读取文本文件中的特定行? - How do I read a specific line on a text file? 如何读取某些内容有换行符的文本文件? - How to read a text file where some of the contents have line breaks? 我如何从 python 中的特定行读取文本文件? - How i can Read text file from a specific line in python? 如何在python中逐行读取文件并逐元素读取列表元素 - How do I read a file line by line and read a list element by element simultaneous in python 如果我有一个字典,其中行的键和内容是文本,如何轻松地将行写入文本文件? - How do I write lines to a text file easily if I have a dictionary with the key of the line and contents being the text?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM