Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Right now I am attempting to open a text document called "temperature.txt" I have saved it on my desktop with the help of a file handler, anyway for reasons unknown I can't get it to work. Could anybody mention to me what I'm doing wrong?

#!/Python34/python

from math import *

fh = open('temperature.txt')

num_list = []

for num in  fh:

    num_list.append(int(num))

fh.close()

1 Answer

0 votes
by (26.4k points)

The pythonic approach 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 have to utilize close here in light of the fact that the 'with' statement handles that consequently. 

On the off chance that you are OK with List comprehensions - this is another strategy : 

#!/Python34/python

with open('temperature.text', 'r') as fh:

    num_list = [int(line) for line in fh]

In the two cases 'temperature.text' should be in your present directry.

Want to become a expert in Python? Join the python course fast!

For more details, do check out the below video tutorial...

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 4, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
0 votes
4 answers

Browse Categories

...