【发布时间】:2014-04-29 08:28:31
【问题描述】:
我想在 Python 3.3 中使用 Windows 中的路径,但出现错误:
FileNotFoundError: [Errno 2] 没有这样的文件或目录: 'E:\\dir\\.project'
问题是双反斜杠。我使用 r 阅读了解决方案。
def f(dir_from):
list_of_directory = os.listdir(dir_from)
for element in list_of_directory:
if os.path.isfile(os.path.join(dir_from, element)):
open(os.path.join(dir_from, element))
f(r'E:\\dir')
我又遇到了这个错误
FileNotFoundError: [Errno 2] 没有这样的文件或目录: 'E:\\dir\\.project'
os.path.normpath(path) 没有解决我的问题。
我做错了什么?
【问题讨论】:
-
双斜线在 Windows 路径中无效。 (除了在开始时表示 SMB 连接到远程服务器或访问非托管文件系统 api)
-
尝试将 '\\' 更改为 '/'
-
另请注意,通过在字符串前面加上
r前缀,您不需要转义反斜杠。请参阅this answer 了解更多信息 -
你正在混合你的变通方法。使用原始字符串 (
r'E:\dir') 或将反斜杠加倍,但不能同时使用。