Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I open a text file in Python?

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.

#!/Python34/python
from math import *

fh = open('temperature.txt')

num_list = []

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

fh.close()
like image 575
Alex Osborne Avatar asked Oct 17 '16 22:10

Alex Osborne


1 Answers

The pythonic way to do this is

#!/Python34/python

num_list = []

with open('temperature.text', 'r') as fh:
    for line in fh:
        num_list.append(int(line))

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

If you are comfortable with List comprehensions - this is another method :

#!/Python34/python

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

In both cases 'temperature.text' must be in your current directory.

like image 133
Tony Suffolk 66 Avatar answered Oct 26 '22 17:10

Tony Suffolk 66