目前我正在尝试打开一个名为“temperature.txt”的文本文件,我使用文件处理程序保存在我的桌面上,但是由于某种原因我无法让它工作。谁能告诉我我做错了什么。
#!/Python34/python
from math import *
fh = open('temperature.txt')
num_list = []
for num in fh:
num_list.append(int(num))
fh.close()
目前我正在尝试打开一个名为“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]
在这两种情况下,“temperature.text”都必须在您的当前目录中。
您只需要在 fh 上使用 .readlines()
像这样:
#!/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()