python - 转义空格的问题?系统找不到路径
问题描述
以下代码:
import os
dirPath = 'f:/x/finance-2020/AI/coursera-CNN/work/week4/Face\ Recognition/weights'
print(dirPath)
X = os.listdir(dirPath)
print(X)
失败如下:
Traceback (most recent call last):
File "test.py", line 6, in <module>
X = os.listdir(dirPath)
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'f:/x/finance-2020/AI/courser
a-CNN/work/week4/Face\\ Recognition/weights'
但是,当在另一个目录中运行时,它可以工作:
import os
dirPath = 'f:/x/finance-2020/AI/coursera-CNN/work/week4'
print(dirPath)
X = os.listdir(dirPath)
print(X)
$ python test.py
f:/x/finance-2020/AI/coursera-CNN/work/week4
['Face Recognition', 'Neural Style Transfer', 'test.py']
我怀疑在转义空白字符时出错,但不知道为什么会发生这种情况。
解决方案
您可以使用常规字符串而不转义空格-
dirPath = 'f:/x/finance-2020/AI/coursera-CNN/work/week4/Face Recognition/weights'
但是,您可以考虑使用os.path
操作来构建健壮的路径 -
dirPath = os.path.join('f:', os.sep, 'x', 'finance-2020', 'AI', 'coursera-CNN',
'work', 'week4', 'Face Recognition', 'weights')
或者更确切地说,不那么冗长,使用pathlib.Path
,正如@Tomerikoo 所建议的那样-
from pathlib import Path
dirPath = Path('f:/x/finance-2020/AI/coursera-CNN/work/week4/Face Recognition/weights')