【问题标题】:Error with double backslash in Windows path in PythonPython中Windows路径中的双反斜杠错误
【发布时间】: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') 将反斜杠加倍,但不能同时使用。

标签: python file backslash


【解决方案1】:

如果您使用的是raw-string,则不要转义反斜杠:

f(r'E:\dir')

当然,这个问题(以及许多其他类似的问题)可以通过在路径中简单地使用正斜杠来解决:

f('E:/dir')

【讨论】:

  • 谢谢!我不知道我们可以在 windows 文件路径中添加正斜杠
【解决方案2】:

将 '\\' 更改为 '/' 对我有用。对于这个例子,我在 C:/ 中创建了一个名为“a”的目录。

>>> (Python interpreter)
>>> import os
>>> os.path.isdir('C:/a/)')
>>> True
>>> os.path.isfile('C:/a/)')
>>> False

【讨论】:

  • 同意,这个 cod 也适用于我,但我想使用 join,我看到错误
猜你喜欢
  • 2020-11-25
  • 1970-01-01
  • 2013-07-23
  • 2014-02-04
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多