问题
我使用以下代码来读取文件并对其进行操作。我为每个函数重用了我的代码的第一位,将数据添加到两个文件中。但是最后一个函数不会将数据添加到我的列表中,即使它是完全相同的代码?它甚至不打印文件的行?
data_laag = open('/Users/arkin/programming/TN_STAID000162.txt')
data_hoog = open('/Users/arkin/programming/TX_STAID000162.txt')
def temp_laag(data):
temp = []
date = []
line_num = 0
for line in data_laag:
if line_num < 22:
line_num += 1
else:
data = line.split(',')
temp.append(float(data[3])/10)
date.append(data[2])
min_temp = 999
for i in temp:
if i < min_temp:
min_temp = i
index = temp.index(min_temp)
print 'De minimum temperatuur ooit gemeten is:' ,min_temp, 'Dit was op de volgende datum', date[index][:4],date[index][4:6],date[index][6:8]
temp_laag(data_laag)
def temp_hoog(data):
temp = []
datum = []
line_num = 0
for line in data_hoog:
if line_num < 22:
line_num += 1
else:
data = line.split(',')
temp.append(float(data[3])/10)
datum.append(data[2])
max_temp = 0
for i in temp:
if i > max_temp:
max_temp = i
index = temp.index(max_temp)
print 'De maximum temperatuur gemeten is', max_temp , 'Dit gebeurd op op de volgende datum', datum[index][:4],datum[index][4:6],datum[index][6:8]
temp_hoog(data_hoog)
def aantal_dagen(data):
temp = []
date = []
line_num = 0
for line in data:
print line
if line_num < 22:
line_num += 1
else:
data = line.split(',')
temp.append(float(data[3])/10)
date.append(data[2])
print temp
aantal_dagen(data_laag)
答案 0 :(得分:1)
有很多选项,最简单的就是更改这两行
data_laag = open('/Users/arkin/programming/TN_STAID000162.txt')
data_hoog = open('/Users/arkin/programming/TX_STAID000162.txt')
到这个
with open('/Users/arkin/programming/TN_STAID000162.txt') as f:
data_laag = list(f)
with open('/Users/arkin/programming/TX_STAID000162.txt') as f:
data_hoog = list(f)
这导致每个文件被打开,读入数组,然后关闭(你缺少的东西)。这意味着每个文件只读一次,数据可以在原始代码中重复使用。
但是你需要处理行结尾等问题。