2

I have a list of URLs and I would like to get the URL from a specific line. For example, from this file bellow:

urls.txt

http://www.google.com
http://www.facebook.com
http://www.stackoverflow.com

I would like to create a function that I give the line number 2, and I get the URL: http://www.facebook.com. Any ideas on how to do it?

rafasalo
  • 243
  • 2
  • 16

2 Answers2

2

You can try something like this.

f=open('urls.txt')
lines=f.readlines()
print(lines[1])

Since the index in python starts from 0 your first line will be 0. Code at line 3 lines[1] is actually pulling the value at second line.

You can also try something like this:

import linecache
linecache.getline('urls.txt', 1)
Dipesh Poudel
  • 429
  • 9
  • 15
  • As this will be a part of a major function, the number "1", from here `lines[1]`, is a variable. Besides I using the TRY/CATCH, do you suggest anything to deal with a number that has no index? In the example above, if the variable is equal to 4, I got the error `IndexError: list index out of range`. – rafasalo Jan 07 '19 at 02:37
  • You got `IndexError: list index out of range` because there is no line 5 (index 4) in the text file. To avoid the issue you can count number of rows at first and check if the given index is bigger than the row count and handle the scenario as per your requirement. – Dipesh Poudel Jan 07 '19 at 03:21
  • thanks! I've posted a new question related to this one, I would appreciate if you can help me: https://stackoverflow.com/questions/54068239/how-to-use-read-next-starting-from-any-line-in-python – rafasalo Jan 07 '19 at 03:30
0

Run a for loop for all the values in list and then compare against the index number. Below code will print the second value from list.

for i in xrange(len(testlist)): if testlist[i] == 2: print i

Don
  • 3,876
  • 10
  • 47
  • 76
ashfon
  • 1