Tim Tim - 3 months ago 17
Python Question

Webbrowser() reading through a text file for URLS

I am trying to write a script to automate browsing to my most commonly visited websites. I have put the websites into a list and am trying to open it using the

webbrowser()
module in Python. My code looks like the following at the moment:

import webbrowser
f = open("URLs", "r")
list = f.readline()
for line in list:
webbrowser.open_new_tab(list)


This only reads the first line from my file "URLs" and opens it in the browser. Could any one please help me understand how I can achieve reading through the entire file and also opening the URLs in different tabs?

Also other options that can help me achieve the same.

Answer

You have two main problems.

The first problem you have is that you are using readline and not readlines. readline will give you the first line in the file, while readlines gives you a list of your file contents.

Take this file as an example:

# urls.txt
http://www.google.com
http://www.imdb.com

Also, get in to the habit of using a context manager, as this will close the file for you once you have finished reading from it. Right now, even though for what you are doing, there is no real danger, you are leaving your file open.

Here is the information from the documentation on files. There is a mention about best practices with handling files and using with.

The second problem in your code is that, when you are iterating over list (which you should not use as a variable name, since it shadows the builtin list), you are passing list in to your webrowser call. This is definitely not what you are trying to do. You want to pass your iterator.

So, taking all this in to mind, your final solution will be:

import webbrowser

with open("urls.txt") as f:
    for url in f:
        webbrowser.open_new_tab(url.strip())

Note the strip that is called in order to ensure that newline characters are removed.