'Read a specific line from a file index

how can I read a specific line from a file?

user.txt:

root
admin
me
you

When I do

def load_user():
       file = open("user.txt", "r")
       nextuser_line = file.readline().strip()
       print(nextuser_line)
       file.close()

root will be printed, but I would like to read admin from the file. So I try to read the next line index using [1]

def load_user():
       file = open("user.txt", "r")
       nextuser_line = file.readline().strip()
       print(nextuser_line[1])
       file.close()

instead of printing 'admin', the output is 'o' from 'root', but not the next line from the file.

what am I doing wrong?



Solution 1:[1]

readline() reads the first line. To access lines through index, use readlines():

def load_user():
    file = open("user.txt", "r")
    lines = file.readlines()
    print(lines[1])
    file.close()
>>> load_user()
'admin'

To remove the \n from the lines, use:

lines = [x.strip() for x in file]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1