python 有关pd.read_csv的问题

jv4diomz  于 2022-10-30  发布在  Python
关注(0)|答案(3)|浏览(225)

我在Windows 10上安装了Anaconda 3。我正在使用pd.read_csv()加载csv文件,但我收到了错误消息。开始,我尝试了df = pd.read_csv('C:\direct_marketing.csv'),它工作正常,文件被导入。
然后我尝试df = pd.read_csv('C:\tutorial.csv'),收到以下错误消息:

Traceback (most recent call last):

  File "<ipython-input-3-ce208cc2684f>", line 1, in <module>
    df = pd.read_csv('C:\tutorial.csv')

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

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

  File "C:\Users\Alexandros_7\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 645, in __init__
    self._make_engine(self.engine)

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

  File "C:\Users\Alexandros_7\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 1213, in __init__
    self._reader = _parser.TextReader(src,**kwds)

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

  File "pandas\parser.pyx", line 628, in pandas.parser.TextReader._setup_parser_source (pandas\parser.c:6861)

OSError: File b'C:\tutorial.csv' does not exist

然后,我将文件移动到一个新文件夹中,重命名它,并再次使用read.csv()导入它:

df = pd.read_csv('C:\Users\test.csv')

这一次我收到了不同的错误消息:

File "<ipython-input-5-03c6d380c174>", line 1
    df = pd.read_csv('C:\Users\test.csv')
                    ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

你能帮助我了解发生了什么事以及如何处理这种情况吗?
多谢了!

of1yzvn4

of1yzvn41#

尝试转义反斜杠:

df = pd.read_csv('C:\\Users\\test.csv')
mspsb9vt

mspsb9vt2#

请尝试使用两个反斜杠“\”而不是“\”。它可能会将反斜杠当作转义符。

vuktfyat

vuktfyat3#

另一种方法是在路径前添加r,即df = pd.read_csv(r'C:\Users\test.csv')

相关问题