以下代码:
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']我怀疑逃避空白角色是个错误,但我不知道为什么会这样。
发布于 2020-11-02 10:41:34
你可以使用普通字符串而不用转义空格-
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')或者,更确切地说,像@Tomerikoo所建议的那样,使用pathlib.Path -
from pathlib import Path
dirPath = Path('f:/x/finance-2020/AI/coursera-CNN/work/week4/Face Recognition/weights')https://stackoverflow.com/questions/64643896
复制相似问题