0

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?

Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29
DeTricke
  • 47
  • 4
  • Does this answer your question? [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – Freddy Mcloughlan May 15 '22 at 11:21

1 Answers1

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]
Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29