How do I open a text file in Python?
<p>Currently I am trying to open a text file called "temperature.txt" i have saved on my desktop using file handler, however for some reason i cannot get it to work. Could anyone tell me what im doing wrong.</p>

<pre><code>#!/Python34/python
from math import *

fh = open('temperature.txt')

num_list = []

for num in  fh:
    num_list.append(int(num))

fh.close()
</code></pre>

<p>The pythonic way to do this is </p>

<pre><code>#!/Python34/python
from math import *

num_list = []

with open('temperature.text', 'r') as fh:
    for line in fh:
        num_list.append(int(line))
</code></pre>

<p>You don't need to use close here because the 'with' statement handles that automatically.</p>

<p>If you are comfortable with List comprehensions - this is another method : </p>

<pre><code>#!/Python34/python
from math import *

with open('temperature.text', 'r') as fh:
    num_list = [int(line) for line in fh]
</code></pre>

<p>In both cases 'temperature.text' must be in your current directory, and I have left the math module import, although neither piece of code needs it</p>

python python-3.x filehandler