-3

A txt file contain several line

I want to get certain line when I give line number

1   bird
2   car
3   computer
4   mobile
5   bike
6   train

ex I give line number 5, and I get bike

Indeed, txt file is just raw data,it does not contain line number

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
kovac
  • 307
  • 4
  • 11
  • Hi, can you please show the code you have already tried? – ofthegoats Sep 17 '19 at 20:34
  • see also other linked questions in the duplicate I suggested – walnut Sep 17 '19 at 20:40
  • I think some question title is difficult to be found. I have search some time,but i still loss it. – kovac Sep 17 '19 at 21:14
  • @kovac I don't agree with the downvotes (at least if they are only for the question being duplicate), but finding the duplicate was quite easy, for example google search `python read specific line` or `python read line by number` or `python read single line` will give you the duplicate in the top results. The search on stackoverflow itself is however much worse in coming up with matching duplicates. – walnut Sep 17 '19 at 21:34

1 Answers1

3

Do this:

# open the file as read only
f = open('your_text_file.txt', "r")

#save it in a list
lines = f.readlines()

#close file to save memory
f.close()

#now you have all lines in a list, you just have to choose a number!

#returns input number as string
number = input("Line number: ")

#int to convert string to integer
#-1 because python arrays start at 0
print(number +" "+ lines[int(number)-1])