无法在Spyder中将本地CSV转换为Pandas数据框

1 投票
1 回答
30 浏览
提问于 2025-04-13 12:49

你好,我正在使用Spyder学习Python(Python 3.8.10 64位 | Qt 5.15.2 | PyQt5 5.15.10 | Windows 10 (AMD64))。我无法把本地的csv文件转换成pandas的数据框。

# import pandas module
import pandas as pd

# making dataframe
df = pd.read_csv("C:\Test\test.txt")

# output the dataframe
print(df)

我已经确认文件夹存在,并且里面有文件。Spyder返回了

df = pd.read_csv("C:\Test\test.txt")
Traceback (most recent call last):

  Cell In[114], line 1
    df = pd.read_csv("C:\Test\test.txt")

  File C:\Program Files\Spyder\pkgs\pandas\io\parsers\readers.py:912 in read_csv
    return _read(filepath_or_buffer, kwds)

  File C:\Program Files\Spyder\pkgs\pandas\io\parsers\readers.py:577 in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)

  File C:\Program Files\Spyder\pkgs\pandas\io\parsers\readers.py:1407 in __init__
    self._engine = self._make_engine(f, self.engine)

  File C:\Program Files\Spyder\pkgs\pandas\io\parsers\readers.py:1661 in _make_engine
    self.handles = get_handle(

  File C:\Program Files\Spyder\pkgs\pandas\io\common.py:859 in get_handle
    handle = open(

OSError: [Errno 22] Invalid argument: 'C:\\Test\test.txt'

我哪里做错了?注意:我几乎是个编程小白。

我尝试过:


!pip install ipython-sql

在上面的命令之前。Spyder输出了一些以

Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: ipython-sql in c:

开头的文本,但其他方面都很稳定。

1 个回答

2

在Python字符串中,反斜杠是一个特殊的字符,它需要被“转义”。反斜杠本身就是用来转义其他字符的,所以在路径中你需要用两个反斜杠,因为Windows系统使用反斜杠作为路径的分隔符。

所以你可以这样写: 'C:\\Test\\test.txt'

你也可以使用“原始”字符串,这样就不需要转义反斜杠了: r'C:\Test\test.txt'

撰写回答