Search code examples
pythonpython-3.xlistfileexternal

How do you only print first 4 strings inside a list?


I have a piece of code that sorts a list of data in an external file and i need to print the first 4 lines that are inside that file.

I have tried searching everywhere with no success.

f=open('SortWin.txt', 'r')
if f.mode == 'r':
winList = f.read()
print('\nHere are the Top 4 Players\n[Score][Name]')
#Need to change winList to only the first 4 names here
print(winList)
f.close()

My external file 'SortWin.txt' looks like this:

11 Tom
16 Tom
18 Ben
20 Tom
21 Ben
23 Tom
36 Tom
42 Tom
45 Tom
46 Tom
98 Ben
99 Tom

The current output is:

11 Tom
16 Tom
18 Ben
20 Tom
21 Ben
23 Tom
36 Tom
42 Tom
45 Tom
46 Tom
98 Ben
99 Tom

I need this to be the output:

11 Tom
16 Tom
18 Ben
20 Tom
21 Ben

Thanks


Solution

  • Now you just have to split and slice the list, just like that:

    #Get 4 elements, splitting for each line
    print( '\n'.join(winList.split('\n')[:4]) )