【问题标题】:pandas.read_csv can't import file with accent mark in pathpandas.read_csv 无法导入路径中带有重音符号的文件
【发布时间】:2018-02-18 18:52:03
【问题描述】:

我正在使用 Python 和 QT GUI 开发应用程序。 我需要将文件导入DataFrame。 我使用QFileDialog.getOpenFileName 获取路径和文件名以使用pandas.read_csv 方法打开它。 一切正常,直到我得到一条带有“ó”之类的特殊字符的路径。 pandas.read_csv 不起作用并导致应用崩溃。

我尝试在控制台中重现错误并得到以下结果:

In[2]: import pandas as pd
Backend Qt5Agg is interactive backend. Turning interactive mode on.

In[3]: path1 = 'F:/Software_Proyects/Python/Proyectos/test_read_csv/FlowData.txt'
In[4]: df1 = pd.read_csv(path1, delim_whitespace=True, dtype=object)

In[5]: path2 = 'F:/Software_Proyects/Python/Proyectos/test_read_csv_with_ó/FlowData.txt'
In[6]: df2 = pd.read_csv(path2, delim_whitespace=True, dtype=object)
Traceback (most recent call last):
  File "C:\Program Files (x86)\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-6-feba8e024d43>", line 1, in <module>
    df2 = pd.read_csv(path2, delim_whitespace=True, dtype=object)
  File "C:\Program Files (x86)\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 646, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "C:\Program Files (x86)\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 389, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "C:\Program Files (x86)\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 730, in __init__
    self._make_engine(self.engine)
  File "C:\Program Files (x86)\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 923, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "C:\Program Files (x86)\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 1390, in __init__
    self._reader = _parser.TextReader(src, **kwds)
  File "pandas\parser.pyx", line 373, in pandas.parser.TextReader.__cinit__ (pandas\parser.c:4184)
  File "pandas\parser.pyx", line 669, in pandas.parser.TextReader._setup_parser_source (pandas\parser.c:8471)
OSError: Initializing from file failed

show_versions() 的输出是:

In[7]: pd.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 3.6.0.final.0
python-bits: 32
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 78 Stepping 3, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None

pandas: 0.19.2
nose: 1.3.7
pip: 9.0.1
setuptools: 27.2.0
Cython: 0.25.2
numpy: 1.11.3
scipy: 0.18.1
statsmodels: 0.6.1
xarray: None
IPython: 5.1.0
sphinx: 1.5.1
patsy: 0.4.1
dateutil: 2.6.0
pytz: 2016.10
blosc: None
bottleneck: 1.2.0
tables: 3.2.2
numexpr: 2.6.1
matplotlib: 2.0.0
openpyxl: 2.4.1
xlrd: 1.0.0
xlwt: 1.2.0
xlsxwriter: 0.9.6
lxml: 3.7.2
bs4: 4.5.3
html5lib: None
httplib2: None
apiclient: None
sqlalchemy: 1.1.5
pymysql: None
psycopg2: None
jinja2: 2.9.4
boto: 2.45.0
pandas_datareader: None

正如我在这篇文章Encoding with pandas.read_csv when file name has accents 中所读到的,问题已在 pandas 0.14.0 中得到修复。

有解决这个问题的建议吗?

【问题讨论】:

  • 试试pd.read_csv(path1, delim_whitespace=True, dtype=object,encoding='utf-8') 或此列表中的其他一些:docs.python.org/3/library/codecs.html#standard-encodings
  • 你可能想检查this issue
  • @Protostome,感谢您的回复,我试过了,但它不起作用。我认为是因为 read_csv 的编码选项是针对文件内容而不是针对文件路径的。文件导入没有问题,文件路径有特殊字符时出现问题
  • 谢谢@MaxU。您的评论为我指明了找到解决方案的方向,我将在下面发布。

标签: python pandas dataframe non-ascii-characters


【解决方案1】:

深入研究,这种行为结合了 Python 3.6 和 pandas.read_csv 仅在 Windows 系统中出现。

Python 3.6 将 Windows 文件系统编码从“mbcs”更改为“UTF-8”。见Python PEP 529。使用sys.getfilesystemencoding()获取当前文件系统编码

我得到了一些解决方案:

1.- 使用此代码将所有应用更改为使用之前的 Python

import sys
sys._enablelegacywindowsfsencoding()

2.- 将文件指针传递给 pandas.read_csv

with open(path2, 'r') as fp:
    df2 = pd.read_csv(fp, delim_whitespace=True, dtype=object)

【讨论】:

  • 太棒了!这个答案对我帮助很大!谢谢
【解决方案2】:

在使用 utf-8 编码阅读之前,您可以在 notebook/ipython 中尝试这些代码行:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

然后在阅读您的文件时按照评论中的建议使用这些行

pd.read_csv(path1, delim_whitespace=True, dtype=object,encoding='utf-8')

【讨论】:

  • 你好@Espoir。我尝试了这个命令,但它不起作用,看看为什么我发现这个命令适用于 Python 2。在 Python 3 中,默认编码是“utf-8”,并且 setdefaultencoding() 方法已从 sys 模块中删除。要在 Python >= 3.4 上使用 reload(sys),我遵循以下示例:stackoverflow.com/questions/961162/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-01
  • 2014-07-25
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 2017-07-15
相关资源
最近更新 更多