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

2024-05-14 12:48:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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)不能解决我的问题。

我做错什么了?


Tags: orpathnofromprojectos错误dir
2条回答

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

f(r'E:\dir')

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

f('E:/dir')

把“\\”改成“/”对我很有用。在本例中,我在C/中创建了一个名为“a”的目录。

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

相关问题 更多 >

    热门问题