Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading