代码之家  ›  专栏  ›  技术社区  ›  matthewr

python误读文件路径名[重复]

  •  -1
  • matthewr  · 技术社区  · 8 年前

    这个问题已经有了答案:

    我想在我的计算机上的l:drive中的一个名为11109的文件夹中遍历多个文件。这是我的剧本:

    for filename in os.listdir('L:\11109'):
        print(filename.split('-')[1])
    

    但是,错误消息返回为:

    File "L:/OMIZ/rando.py", line 12, in <module>
    for filename in os.listdir('L:\11109'):
    
    FileNotFoundError: [WinError 3] The system cannot find the path specified: 
    'L:I09'
    

    它读取了L:\ 11109,但错误消息说指定的路径是L:I09?

    2 回复  |  直到 8 年前
        1
  •  1
  •   IonicSolutions    8 年前

    您需要使用原始字符串或转义反斜杠,否则 \111 决心 I 以下内容:

    a = 'L:\11109'
    print(a)  # shows that indeed 'L:I09'
    
    b = r'L:\11109'
    print(b)  # prints 'L:\11109'
    
    c = 'L:\\11109'  # will be understood correctly by open()
    
        2
  •  0
  •   Sreeram TP    8 年前

    要解决这个问题你可以这样做

    for filename in os.listdir('L:/11109'):
        print(filename.split('-')[1])