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

时间:2020-06-09 20:07:33

标签: python atom-editor

我已经在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
FileNotFoundError: [Errno 2] File C:\Users\wotesi\Documents\Cloud\Documents\Python\Programmas\panda\failu_nosaukumi.csv does not exist: 'C:\\Users\\wotesi\\Documents\\Cloud\\Documents\\Python\\Programmas\\panda\\failu_nosaukumi.csv'

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

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

from pathlib import Path
path_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()