How to read a text file into a string and print out index 1 for link 2 info?

I have a test file contains multiple lines for names.

For example:

Andy
Kevin
Lisa
Mike

I tried to use the below code to read them into a string. And print second line names by using index.

with open("....names.txt", 'r') as f:
names = f.read().replace('n ', "")
print(names[1])

but when I do this, the index1 print out is n instead of second link info. What I should change to make it the same as the code below:

names = ["Andy", "Kevin", "Lisa", "Mike"]
print(names[1])

Thank you.

Answer

names = []
with open("....names.txt", 'r') as f:
  for line in f:
    names.append(line.strip())
    
print(names[1])

or using a list comprehension:

with open("....names.txt", 'r') as f:
  names = [line.strip() for line in f]

Leave a Reply

Your email address will not be published. Required fields are marked *