【问题标题】:Failing to continually save and update a .CSV file after a period of time一段时间后无法持续保存和更新 .CSV 文件
【发布时间】: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


【解决方案1】:

如果draw.stdin.write() 阻塞,可能意味着您没有及时消费draw.stdout。由于操作系统管道缓冲区已满,文档会警告死锁。

如果您不需要输出,您可以设置 stdout=devnull where devnull = open(os.devnull, 'wb') 否则有几种方法可以在不阻塞代码的情况下读取输出:线程、选择、tempfile.TemoraryFile

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    相关资源
    最近更新 更多