我有一些数据文件包含流量数据。例如,
9/12/1999 0
13/12/1999 2544
14/12/1999 2552
15/12/1999
16/12/1999
18/12/1999 3039
19/12/1999 3043
我编写了一个代码来读取所有数据文件并写入具有该格式的新输出文件 Date Flow1 Flow2等。
我也在连续日期写了它(那里没有该日期的数据,将0写入输出文件)。我在下面的脚本中没有包含这一点。
我遇到的问题是,当数据文件中有一行日期但没有流数据时(例如上例中的第4行,第5行)。代码给出了该行的空白值而不是0.我认为这是一件简单的事情,但我无法弄明白。任何人都可以帮助我吗? 我的代码是
for Qfilename in Q_filenamelist:
Qfileopen = open(Qfilename,'r')
for line in Qfileopen:
line = line.rstrip()
if not line.startswith("and") and not line.startswith("Time") and not line.startswith("Date"): #ignore headers
Qwordslist = line.split(',')
time = Qwordslist[0]
flow = Qwordslist[1]
if not time in time_list:
time_list.append(time)
index = time+" "+Qfilename
Qourdict[index] = flow
Qfileopen.close()
time_list.sort(key=lambda x: datetime.strptime(x,'%d/%m/%Y'))
#write output data
outfile = open(outfilename,'w')
outfile.write("Date,")
for Qfilename in Q_filenamelist:
Qfilename = Qfilename.split(".")[0]
outfile.write(Qfilename+',')
outfile.write('\n')
for time in time_list:
outfile.write(time+',')
for Qfilename in Q_filenamelist:
index = time+" "+Qfilename
grabflow = Qourdict.get(index,"0.0")
if grabflow == " ":
outfile.write("0.0"+',')
else:
outfile.write(str(grabflow)+',')
outfile.write('\n')
outfile.close()
非常感谢。
答案 0 :(得分:0)
作为猜测,您可以尝试:
Qourdict[index] = flow if flow.strip() else '0'
而不是:
Qourdict[index] = flow
没有太多事情要继续......