如何在熊猫中读取具有完整路径的csv文件

我在 Python 中得到了这段代码:


import pandas as pd

from pathlib import Path


path_1 = Path('C:/Users/wotesi/Documents/Cloud/Documents/Python/Programmas/panda/')

print(path_1)

full_path = path_1.joinpath('failu_nosaukumi.csv')

print(full_path)

我得到了实际结果(文件的完整路径和文件名),但是当我尝试读取该文件时:


faili = pd.read_csv(full_path, header=None, index_col=0).reset_index()

我收到错误:


Traceback (most recent call last):

  File "C:\Users\wotesi\AppData\Local\Temp\atom_script_tempfiles\d35090b0-aa8b-11ea-bb80-793ba6a5bb7c", line 19, in <module>

    faili = pd.read_csv(full_path, header=None, index_col=0).reset_index()

  File "C:\Users\wotesi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\parsers.py", line 676, in parser_f

    return _read(filepath_or_buffer, kwds)

  File "C:\Users\wotesi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\parsers.py", line 448, in _read

    parser = TextFileReader(fp_or_buf, **kwds)

  File "C:\Users\wotesi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\parsers.py", line 880, in __init__

    self._make_engine(self.engine)

  File "C:\Users\wotesi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\parsers.py", line 1114, in _make_engine

    self._engine = CParserWrapper(self.f, **self.options)

  File "C:\Users\wotesi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\parsers.py", line 1891, in __init__

    self._reader = parsers.TextReader(src, **kwds)

  File "pandas\_libs\parsers.pyx", line 374, in pandas._libs.parsers.TextReader.__cinit__

  File "pandas\_libs\parsers.pyx", line 674, in pandas._libs.parsers.TextReader._setup_parser_source

此外 - 当我使用 Anaconda/Spyder 运行相同的代码(没有完整路径,只是所有文件都在同一目录中)时,我没有收到任何错误。此错误在 Atom 中生成。如何修改代码使其在 Atom 中也能运行?此外,当我将该代码编译为 exe 模块并尝试从其他 Windows 机器运行时,它也会给出相同的错误消息 - 找不到文件。任何解决方案都适合我。谢谢!


慕后森
浏览 115回答 1
1回答

摇曳的蔷薇

你可以尝试这样的事情:from pathlib import Pathpath_1 = Path(r'C:\Users\wotesi\Documents\Cloud\Documents\Python\Programmas\panda')faili = pd.read_csv(path_1.joinpath('failu_nosaukumi.csv'), header=None, index_col=0).reset_index()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python