将.csv文件解析为dataframe并获取ValueError:没有要从文件

时间:2016-04-09 20:19:58

标签: python python-3.x

我正在将许多cvs文件中的特定列解析为一个数据帧。但是我收到一个错误:

ValueError:没有要从文件中解析的列

如果它有用,我可以发布整个堆栈跟踪。

我认为错误源于尝试读取没有数据的csv(只是一个空文件),并想知道如何解决这个问题?我的代码如下:

def getTimeseriesData(DataPath,columnNum):
    colNames = ['date']

    path = DataPath
    filePath = path, "*.csv"
    allfiles = glob.glob(os.path.join(path, "*.csv"))
    for fname in allfiles:
        name = os.path.splitext(fname)[0]
        name = os.path.split(name)[1]

        colNames.append(name)
    print(colNames)

    dataframes = [pd.read_csv(fname, header=None,usecols=[0,columnNum]) for fname in allfiles]
    print(dataframes)    

    reduce(partial(pd.merge, on=0, how='outer'), dataframes)

    timeseriesData = reduce(partial(pd.merge, on=0, how='outer'), dataframes)


    timeseriesData.columns=colNames

    return timeseriesData

我的完整堆栈跟踪如下:

  File "C:\Users\Documents\scripts\AuctionStrategy_2.1.py", line 340, in <module>
    main()

  File "C:\Users\Documents\scripts\AuctionStrategy_2.1.py", line 39, in main
    stockData = getTimeseriesData2(rawTimeseriesDataPath,1)

  File "C:\Users\Documents\scripts\AuctionStrategy_2.1.py", line 88, in getTimeseriesData2
    dataframes = [pd.read_csv(fname, header=None,usecols=[0,columnNum]) for fname in allfiles]

  File "C:\Users\Documents\scripts\AuctionStrategy_2.1.py", line 88, in <listcomp>
    dataframes = [pd.read_csv(fname, header=None,usecols=[0,columnNum]) for fname in allfiles]

  File "C:\WinPython-64bit-3.4.4.1\python-3.4.4.amd64\lib\site-packages\pandas\io\parsers.py", line 498, in parser_f
    return _read(filepath_or_buffer, kwds)

  File "C:\WinPython-64bit-3.4.4.1\python-3.4.4.amd64\lib\site-packages\pandas\io\parsers.py", line 275, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)

  File "C:\WinPython-64bit-3.4.4.1\python-3.4.4.amd64\lib\site-packages\pandas\io\parsers.py", line 590, in __init__
    self._make_engine(self.engine)

  File "C:\WinPython-64bit-3.4.4.1\python-3.4.4.amd64\lib\site-packages\pandas\io\parsers.py", line 731, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)

  File "C:\WinPython-64bit-3.4.4.1\python-3.4.4.amd64\lib\site-packages\pandas\io\parsers.py", line 1103, in __init__
    self._reader = _parser.TextReader(src, **kwds)

  File "pandas\parser.pyx", line 518, in pandas.parser.TextReader.__cinit__ (pandas\parser.c:5030)

ValueError: No columns to parse from file

任何帮助非常感谢

1 个答案:

答案 0 :(得分:1)

自从我上次使用python已经有几年了,但我会抓住异常并从那里处理它。

来自python文档

Handling exceptions

编辑:

来自stackoverflow的

Try/Except in Python: How do you properly ignore Exceptions?

文件夹中是否有0字节大小的CSV文件?

最好的问候