使用Pandas加载CSV文件触发FileNotFoundError问题求助
Pandas加载CSV触发FileNotFoundError的排查与解决
问题详情
运行Pandas加载CSV文件的代码时触发FileNotFoundError,报错堆栈及代码如下:
报错堆栈
FileNotFoundError Traceback (most recent call last) /tmp/ipykernel_83/222635537.py in <module> 3 import numpy as np 4 #Load the data ----> 5 df = pd.read_csv(r'C:\Users\Admin\Desktop\Vrinda_Store_2022.csv') 6 print(df) /opt/conda/lib/python3.9/site-packages/pandas/util/_decorators.py in wrapper(*args, **kwargs) 309 stacklevel=stacklevel, 310 ) --> 311 return func(*args, **kwargs) 312 313 return wrapper /opt/conda/lib/python3.9/site-packages/pandas/io/parsers/readers.py in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, error_bad_lines, warn_bad_lines, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options) 584 kwds.update(kwds_defaults) 585 --> 586 return _read(filepath_or_buffer, kwds) 587 588 /opt/conda/lib/python3.9/site-packages/pandas/io/parsers/readers.py in _read(filepath_or_buffer, kwds) 480 481 # Create the parser. --> 482 parser = TextFileReader(filepath_or_buffer, **kwds) 483 484 if chunksize or iterator: /opt/conda/lib/python3.9/site-packages/pandas/io/parsers/readers.py in __init__(self, f, engine, **kwds) 809 self.options["has_index_names"] = kwds["has_index_names"] 810 --> 811 self._engine = self._make_engine(self.engine) 812 813 def close(self): /opt/conda/lib/python3.9/site-packages/pandas/io/parsers/readers.py in _make_engine(self, engine) 1038 ) 1039 # error: Too many arguments for "ParserBase" --> 1040 return mapping[engine](self.f, **self.options) # type: ignore[call-arg] 1041 1042 def _failover_to_python(self): /opt/conda/lib/python3.9/site-packages/pandas/io/parsers/c_parser_wrapper.py in __init__(self, src, **kwds) 49 50 # open handles --> 51 self._open_handles(src, kwds) 52 assert self.handles is not None 53 /opt/conda/lib/python3.9/site-packages/pandas/io/parsers/base_parser.py in _open_handles(self, src, kwds) 220 Let the readers open IOHandles after they are done with their potential raises. 221 """ --> 222 self.handles = get_handle( 223 src, 224 "r", /opt/conda/lib/python3.9/site-packages/pandas/io/common.py in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options) 700 if ioargs.encoding and "b" not in ioargs.mode: 701 # Encoding --> 702 handle = open( 703 handle, 704 ioargs.mode, FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Admin\\Desktop\\Vrinda_Store_2022.csv'
运行代码
import pandas as pd import numpy as np #Load the data df = pd.read_csv(r'C:\Users\Admin\Desktop\Vrinda_Store_2022.csv') print(df)
解决步骤
1. 排查路径环境冲突
从报错路径/opt/conda可以看出,代码运行在Linux环境,但你使用了Windows格式的C:\路径,这是核心问题——Linux系统没有C:盘,无法识别该路径。需要:
- 将CSV文件上传到Linux环境的对应目录(比如
/home/你的用户名/Desktop/) - 修改代码中的路径为Linux格式,例如:
df = pd.read_csv('/home/用户名/Desktop/Vrinda_Store_2022.csv')
2. 验证文件真实存在
- 如果是Windows环境,打开文件资源管理器,粘贴路径
C:\Users\Admin\Desktop\Vrinda_Store_2022.csv,确认能直接打开文件 - 如果是Linux环境,执行命令
ls /目标路径/Vrinda_Store_2022.csv,确认文件存在
3. 优化路径写法(跨平台兼容)
使用Python内置的os.path模块自动适配系统路径:
import pandas as pd import os # 替换成对应系统的正确路径片段 file_path = os.path.join("Users", "Admin", "Desktop", "Vrinda_Store_2022.csv") # Linux环境可写成 os.path.join("/home", "用户名", "Desktop", "Vrinda_Store_2022.csv") df = pd.read_csv(file_path)
或者直接把CSV文件放在代码同目录下,简化路径:
df = pd.read_csv("Vrinda_Store_2022.csv")
内容的提问来源于stack exchange,提问作者user22682926
相关产品推荐
相关产品推荐

