Webbrowser() reading through a text file for URLS
<p>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 <code>webbrowser()</code> module in Python. My code looks like the following at the moment:</p>

<pre><code>import webbrowser                                                                                
f = open("URLs", "r")
list = f.readline()
for line in list:
    webbrowser.open_new_tab(list)
</code></pre>

<p>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?</p>

<p>Also other options that can help me achieve the same.</p>

<p>You have two main problems. </p>

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

<p>Take this file as an example: </p>

<pre><code># urls.txt
http://www.google.com
http://www.imdb.com
</code></pre>

<p>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. </p>

<p><a href="https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow">Here</a> is the information from the documentation on files. There is a mention about best practices with handling files and using <code>with</code>. </p>

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

<p>So, taking all this in to mind, your final solution will be: </p>

<pre><code>import webbrowser

with open("urls.txt") as f:
    for url in f:
        webbrowser.open_new_tab(url.strip())
</code></pre>

<p>Note the <code>strip</code> that is called in order to ensure that newline characters are removed. </p>

python python-2.7 python-webbrowser