user15484723
user15484723

Reputation:

How to fetch text file data in a variable in python?

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”)

Upvotes: 0

Views: 2674

Answers (2)

Mohammad Taghdir
Mohammad Taghdir

Reputation: 9

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()

Upvotes: 1

scotty3785
scotty3785

Reputation: 7006

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

Upvotes: 1

Related Questions