Search code examples
python-3.xfilefindreadlines

How to get a phrase from a line number in python?


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?


Solution

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