0

In python how we can select second line string of a text file.

I have a text file and in that file there are some data in line by line_

Dog
Cat
Cow

How to fetch the second line which is “Cat” and store that string in a variable.

f = open(“text_file.txt”, “r”)
var =    # “Cat”

Can I use single line code without using any loop or anything like we open a file using this single line of code f = open(“text_file.txt”, “r”)

4
  • 1
    var = f.readlines()[1] Commented Mar 26, 2021 at 8:41
  • Sir when i run this code f = open("cred.txt", "r") apikey = f.readlines()[1] client_token = f.readlines()[2] password = f.readlines()[3] print(apikey) print(client_token) print(password) i'm getting error like this Traceback (most recent call last): File "C:\Users\Nayan\PycharmProjects\Angel_Broking\main.py", line 9, in <module> client_token = f.readlines()[2] IndexError: list index out of range Commented Mar 26, 2021 at 9:10
  • index 1 not 2 mean can you please elaborate sir i can't understand Commented Mar 26, 2021 at 9:20
  • You asked for a 1-line solution to get the 2nd line. readlines()[1] will give you the 2nd line of the file, not the 1st: readlines()[0] will give you the 1st. But now it appears you wanted to get several lines from the file, not just one. That can't be done in a single line because you can only call readlines() once on an open file. The first time reads all of the lines in the file and gives you back a list of them. That uses the lines up, and calling readlines() again will give you an empty list. So: mylist = f.readlines(); apikey=mylist[0]; client_token=mylist[1] etc. Commented Mar 26, 2021 at 9:57

2 Answers 2

1

I'd suggest the following

with open('anim.txt','r') as f:
    var = f.readlines()[1].strip()

print(var)
  • [1] get the second line
  • .strip() removes the new line character from the end of the string
  • with open... safely opens/closes the file
Sign up to request clarification or add additional context in comments.

Comments

1

Open your file in this mode:

f = open('x.txt','r+',encoding='utf-8')

You can then read the files line by line:

f.readlines()

1 Comment

Sir when i run this code f = open('cred.txt', 'r+', encoding='utf-8') apikey = f.readlines()[1] client_token = f.readlines()[2] password = f.readlines()[3] print(apikey) print(client_token) print(password) i'm getting error like this Traceback (most recent call last): File "C:\Users\Nayan\PycharmProjects\Angel_Broking\main.py", line 9, in <module> client_token = f.readlines()[2] IndexError: list index out of range

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.