Python 3.7中如何打开路径含特殊字符é的文件?读取报错求助
解决含特殊字符é的网络共享路径文件访问问题
针对你遇到的带é字符的SMB共享路径无法被xarray识别的问题,给你几个可行的解决思路:
改用原始字符串+Windows UNC路径格式
把路径改成反斜杠的UNC格式,同时用原始字符串避免转义问题,再传给xarray:import xarray as xr # 用原始字符串定义UNC路径,反斜杠不需要转义 file_path = r"\\business\Partage\city\Données\climate\amplitude_1950-01-01.nc" data = xr.open_dataset(file_path)借助pathlib的Windows路径类处理
Python 3.7的pathlib提供了专门处理Windows路径的类,强制按Windows规则解析路径:from pathlib import PureWindowsPath import xarray as xr # 定义Windows格式路径 win_path = PureWindowsPath(r"\\business\Partage\city\Données\climate\amplitude_1950-01-01.nc") data = xr.open_dataset(str(win_path))通过文件系统编码转换路径
利用系统的文件系统编码重新编码路径,匹配底层调用的编码要求:import sys import xarray as xr file_path = "//business/Partage/city/Données/climate/amplitude_1950-01-01.nc" # 按系统文件编码转换路径 encoded_path = file_path.encode(sys.getfilesystemencoding()).decode(sys.getfilesystemencoding()) data = xr.open_dataset(encoded_path)绕过xarray直接用netCDF4打开
如果xarray的路径解析有问题,先直接用netCDF4库打开文件对象,再传给xarray:import netCDF4 as nc import xarray as xr # 先通过netCDF4打开数据集 nc_ds = nc.Dataset("//business/Partage/city/Données/climate/amplitude_1950-01-01.nc") data = xr.open_dataset(nc_ds)
另外可以检查VS Code的终端编码设置,把terminal.integrated.encoding改成utf-8,避免终端编码干扰路径解析。
内容的提问来源于stack exchange,提问作者corp_guy
相关产品推荐
相关产品推荐

