看似相同的路径为何触发OSError?SQLAlchemy与os路径问题排查
问题描述
通过SQLAlchemy查询生成路径A:
with engine.connect() as conn: path_a = conn.execute(some_select_statement).scalar()
通过os模块拼接目录生成路径B:
path_b = os.path.join(main_path, user_id)
打印path_a和path_b时,显示结果完全一致:
\\network_dir\dir1\dir2\dir3
但将两个路径传入调用os.stat()的函数getFilesFromPath时,path_a触发错误,path_b可正常运行,且终端直接调用os.stat()也无错误。
函数getFilesFromPath代码如下:
def getFilesFromPath(list_of_path_of_dir_or_files): result = [] for path in list_of_path_of_dir_or_files: if os.path.isdir(path): for root, dirs, files in os.walk(path): for name in files: full_path = os.path.abspath(os.path.join(root, name)) if os.stat(full_path).st_size > 0: result.append(full_path) elif os.path.isfile(path): result.append(os.path.abspath(path))
错误信息:
OSError: [WinError 59] An unexpected network error occurred: '\\network_dir\dir1\dir2\dir3\file_name.ext'
错误触发在代码行:if os.stat(full_path).st_size > 0:
原因分析与解决方案
核心问题是路径字符串存在隐形字符差异:
- path_b由
os.path.join生成,是Python原生处理的字符串,无隐形控制字符; - path_a来自数据库查询,大概率携带了不可见的空白字符(比如末尾的换行符
\n、回车符\r,或是全角空格),这些字符打印时不会显示,但会干扰系统对路径的解析。
当os.walk处理带隐形字符的path_a时,拼接出的full_path实际包含这些隐形字符,导致系统识别路径时出现异常,触发网络路径错误。而终端手动输入的路径没有这些字符,所以能正常运行。
验证方法
打印两个路径的长度,或用repr()查看原始字符串结构:
print(len(path_a), len(path_b)) print(repr(path_a)) print(repr(path_b))
如果path_a长度更长,或repr输出里多了\n/\r之类的字符,即可确认问题。
解决办法
对从数据库获取的路径做清洗,去除首尾空白字符:
path_a = conn.execute(some_select_statement).scalar().strip()
若存在全角空格或其他特殊隐形字符,可进一步用正则清理:
import re path_a = re.sub(r'\s+', '', conn.execute(some_select_statement).scalar())
内容的提问来源于stack exchange,提问作者Rico
相关产品推荐
相关产品推荐

