运行python pd.read_csv代码时收到错误消息

时间:2019-12-16 20:16:13

标签: python pandas

当我尝试运行以下代码以读取位于C驱动器中的CSV文件时:

import pandas as pd


fd_inspections = pd.read_csv('c:\food_inspections.csv')

我收到此错误

runfile('C:/food_inspections.py', wdir='C:')
Traceback (most recent call last):

  File "<ipython-input-5-369bc957a5c4>", line 1, in <module>
    runfile('C:/food_inspections.py', wdir='C:')

  File "C:\anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
    execfile(filename, namespace)

  File "C:\anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/food_inspections.py", line 13, in <module>
    fd_inspections =pd.read_csv('c:\food_inspections.csv')

  File "C:\anaconda\lib\site-packages\pandas\io\parsers.py", line 655, in parser_f
    return _read(filepath_or_buffer, kwds)

  File "C:\anaconda\lib\site-packages\pandas\io\parsers.py", line 405, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)

  File "C:\anaconda\lib\site-packages\pandas\io\parsers.py", line 764, in __init__
    self._make_engine(self.engine)

  File "C:\anaconda\lib\site-packages\pandas\io\parsers.py", line 985, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)

  File "C:\anaconda\lib\site-packages\pandas\io\parsers.py", line 1605, in __init__
    self._reader = parsers.TextReader(src, **kwds)

  File "pandas/_libs/parsers.pyx", line 394, in pandas._libs.parsers.TextReader.__cinit__ (pandas\_libs\parsers.c:4209)

  File "pandas/_libs/parsers.pyx", line 710, in pandas._libs.parsers.TextReader._setup_parser_source (pandas\_libs\parsers.c:8873)

FileNotFoundError: File b'c:\x0cood_inspections.csv' does not exist

为什么要尝试读取代码中没有的其他文件名?

3 个答案:

答案 0 :(得分:2)

  • 只需将r''放在文件路径之前。因为\逃脱了字符。
  • 另一种方法是在字符串中使用\\来转义该\
import pandas as pd
fd_inspections = pd.read_csv(r'c:\food_inspections.csv')

答案 1 :(得分:1)

尝试打印出文件路径。

print('c:\food_inspections.csv')

它返回以下内容:

c:\x0cood_inspections.csv

发生这种情况是因为您的字符串中有\ f,它具有特殊含义。尝试使用原始字符串:

fd_inspections = pd.read_csv(r'c:\food_inspections.csv')

这应该有效。

答案 2 :(得分:0)

反斜杠是python中的转义字符。

编写文件路径时,您需要将它们加倍或使用正斜杠...

fd_inspections = pd.read_csv('c:\\ food_inspections.csv')

或(更整洁,因此更可取的选择)

fd_inspections = pd.read_csv('c:/food_inspections.csv')