目前,我正在尝试打开一个名为“Temperature.txt”的文本文件,我已使用文件处理程序保存在桌面上,但是由于某种原因我无法使其工作。谁能告诉我我做错了什么。
#!/Python34/python
from math import *
fh = open('temperature.txt')
num_list = []
for num in fh:
num_list.append(int(num))
fh.close()
执行此操作的 pythonic 方法是
#!/Python34/python
num_list = []
with open('temperature.text', 'r') as fh:
for line in fh:
num_list.append(int(line))
您不需要在此处使用 close,因为“with”语句会自动处理该问题。
如果您对列表理解感到满意 - 这是另一种方法:
#!/Python34/python
with open('temperature.text', 'r') as fh:
num_list = [int(line) for line in fh]
在这两种情况下,“温度.文本”必须位于当前目录中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)