在Python中读取和写入文件时出错

时间:2016-09-12 17:04:43

标签: python

我正在尝试将文件从一种格式转换为另一种格式。当前格式是DAQ(数据采集格式),首先读取。然后我使用undaq Tools模块将文件写入hdf5格式。

import glob
ctnames = glob.glob('*.daq')

以下是几个文件名(总共有100个):

ctnames
['Cars_20160601_01.daq',
 'Cars_20160601_02.daq',
 'Cars_20160601_03.daq',
 'Cars_20160601_04.daq',
 'Cars_20160601_05.daq',
 'Cars_20160601_06.daq',
 'Cars_20160601_07.daq',
.
.
.
## Importing undaq tools:
from undaqTools import Daq

读取DAQ文件并写入hdf5:

for n in ctnames:     
   x = daq.read(n)
   daq.write_hd5(x) 

以下是我得到的错误:

C:\Anaconda3\envs\py27\lib\site-packages\undaqtools-0.2.3-py2.7.egg\undaqTools\daq.py:405: RuntimeWarning: Failed loading file on frame 46970. (stopped reading file)
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-17-6fe7a8c9496d> in <module>()
      1 for n in ctnames:
----> 2    x = daq.read(n)
      3    daq.write_hd5(x)

C:\Anaconda3\envs\py27\lib\site-packages\undaqtools-0.2.3-py2.7.egg\undaqTools\daq.pyc in read_daq(self, filename, elemlist, loaddata, process_dynobjs, interpolate_missing_frames)
    272 
    273         if loaddata:
--> 274             self._loaddata()
    275             self._unwrap_lane_deviation()
    276 

C:\Anaconda3\envs\py27\lib\site-packages\undaqtools-0.2.3-py2.7.egg\undaqTools\daq.pyc in _loaddata(self)
    449                         assert tmpdata[name].shape[0] == frame.frame.shape[0]
    450                     else:
--> 451                         assert tmpdata[name].shape[1] == frame.frame.shape[0]
    452 
    453         # cast as Element objects

AssertionError:  

问题

我有两个问题:
1.我如何知道100个文件中的哪一个引发错误?
2.如果他们抛出错误我如何跳过文件?

1 个答案:

答案 0 :(得分:1)

read()调用换入try / except块。如果出现异常,请打印当前文件名并跳到下一个文件名。

for n in ctnames:     
    try:
        x = daq.read(n)
    except AssertionError:
        print 'Could not process file %s.  Skipping.' % n
        continue
    daq.write_hd5(x)