Python中Pandas报EmptyDataError: No columns to parse from file的一种原因

使用Pyhton的Pandas模块时报EmptyDataError: No columns to parse from file。什么原因。先上原来的错误代码:

 with open(datafile, 'w', newline='',encoding='utf-8') as wf: writer = csv.writer(wf) writer.writerow(colsname) for quotes in getdatas: row =[quotes['Date'],quotes['Open'],quotes['High'],quotes['Low'],quotes['Close'],quotes['Volume']] writer.writerow(row) quotes = pandas.read_csv(datafile, engine='python', index_col=0,parse_dates=True, infer_datetime_format=True)

结果毫不留情的报错。

网上查了查,大家把关注点放到了read_csv()上了。
主要的解决方法为:

  1. 按报错信息查看对应的CSV文件是否存在,是否为空,是否格式正确
  2. 如果自信代码没问题,就pass掉报错。

但是出问题的代码查了都不是这些情况。究竟哪里错了呢。
原来read_csv()所在行与写入csv文件的循环在同一列上对齐了。这就是说,写入cvs后,还没有关闭文件,就企图打开csv进行读操作,结果发生了独占性错误。

找到了问题的根源就好修改了。把read_csv()所在的行提前到与最初的with对齐,这样就可以在with完成写操作,并关闭文件后,再read_csv()了,从而避免报EmptyDataError: No columns to parse from file
这样正确代码就应该是:

with open(datafile, 'w', newline='',encoding='utf-8') as wf:writer = csv.writer(wf)writer.writerow(colsname)for quotes in getdatas:row =[quotes['Date'],quotes['Open'],quotes['High'],quotes['Low'],quotes['Close'],quotes['Volume']]writer.writerow(row)quotes = pandas.read_csv(datafile, engine='python', index_col=0, parse_dates=True, infer_datetime_format=True)

所以出现:EmptyDataError: No columns to parse from file 也有可能是,出现了文件被其他程序打开,占用的情况。