Reputation:
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
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
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 stringwith open...
safely opens/closes the fileUpvotes: 1