【发布时间】:2012-12-31 08:25:15
【问题描述】:
我编写了一个小程序,它在每个小步舞曲中从两件设备中读取值,然后将其保存到 .csv 文件中。我希望在每次收集每个点后更新和保存文件,这样如果电脑崩溃或发生其他问题,就不会发生数据丢失。为此,我打开文件(ab 模式),使用写入行并循环关闭文件。集合之间的时间约为 1 分钟。这很好用,但问题是在数据收集 5-6 小时后,它停止保存到 .csv 文件,并且没有出现任何错误,代码继续运行,图形正在更新,就像什么都没发生一样,但打开.csv 文件显示数据丢失。我想知道我使用的代码是否有问题。我也不应该从中运行一个进行实时绘图的子进程,但我认为这不会引起问题......我也添加了这些代码行。
##Initial file declaration and header
with open(filename,'wb') as wdata:
savefile=csv.writer(wdata,dialect='excel')
savefile.writerow(['System time','Time from Start(s)','Weight(g)','uS/cm','uS','Measured degC','%/C','Ideal degC','/cm'])
##Open Plotting Subprocess
draw=subprocess.Popen('TriPlot.py',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
##data collection loop
while True:
Collect Data x and y
Waits for data about 60 seconds, no sleep or pause commoand used, pyserial inteface is used.
## Send Data to subprocess
draw.stdin.write('%d\n' % tnow)
draw.stdin.write('%d\n' % s_w)
draw.stdin.write('%d\n' % tnow)
draw.stdin.write('%d\n' % float(s_c[5]))
##Saving data Section
wdata=open(filename,'ab')
savefile=csv.writer(wdata,dialect='excel')
savefile.writerow([tcurrent,tnow,s_w,s_c[5],s_c[7],s_c[9],s_c[11],s_c[13],s_c[15]])
wdata.close()
P.S 此代码使用以下包用于未显示的代码。 pyserial、csv、os、subprocess、Tkinter、string、numpy、time 和 wx。
【问题讨论】:
-
您可以打开文件名一次,然后在循环结束时调用
wdata.flush()(您可以添加os.fsync(wdata),这在极少数情况下可能会有所帮助) -
如果你只写 1000 次虚拟数据,你能重现它吗?
-
J.F 我将尝试重现写入一个长数据文件。对于 .flush() 我会将 wdata=open 和 savefile=csv.writer 移出循环,然后在循环中调用 savefile.writerow() 后跟 wdata.flush()?
-
是的,
.writerow(); .flush() -
您是否考虑过使用
logging库?这比自己滚动要容易。
标签: python csv collections export-to-csv