简体   繁体   中英

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. I'm trying using for loops and setting conditions but I'm still not sure. The text file content is:

Highest Goal Scorers 2018

Country

Australia, 529

Jamaica, 466

England, 450

New Zealand, 391

South Africa, 363

And I'm trying to return and output that looks like this:

'Highest Goal Scorers 2018',

'Country'

['Australia, 529\n', 'Jamaica, 466\n', 'England, 450\n', 'New Zealand, 391\n', 'South Africa, 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:])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM