How do I open a text file in Python?

二次信任 提交于 2020-12-29 19:47:27

问题


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()

回答1:


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.




回答2:


You simply need to use .readlines() on fh

like this:

#!/Python34/python
from math import *

fh = open('temperature.txt')

num_list = []

read_lines = fh.readlines()
for line in read_lines:
    num_list.append(int(line))

fh.close()


来源:https://stackoverflow.com/questions/40096612/how-do-i-open-a-text-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!