python - Python 中 Windows 路径中的双反斜杠错误

标签 python file backslash

<分区>

我想在 Python 3.3 中使用 Windows 中的路径,但出现错误:

FileNotFoundError: [Errno 2] No such file or directory: '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] No such file or directory: 'E:\\dir\\.project'

os.path.normpath(path) 没有解决我的问题。

我做错了什么?

最佳答案

如果您使用的是 raw-string , 那么你就不会转义反斜杠:

f(r'E:\dir')

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

f('E:/dir')

关于python - Python 中 Windows 路径中的双反斜杠错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22567785/

相关文章:

python - 如何一次运行最多 10 个线程?

python - 将 UTC 时间字符串的 pandas 数据帧列转换为 float

javascript - 带有 Javascript 的表情符号代理字符串。如何解析?

C++ 字符串函数只返回某些字符

java - 如何在java中用 "\"替换 "\\"

python - 验证失败后从空表单数据中检索空字符串

java - 多文件输入,用stdin//Argparse4j,Java

file - 如何在 Yesod 中为静态文件启用 'Access-Control-Allow-Origin' header ?

c - 以下 C 程序的输出是什么以及如何输出?

python - `os.system` 产生 256 的倍数?