Python 2.7 列出目录中有“-&引用;目录名中的字符

Python 2.7 列出目录中有“-&引用;目录名中的字符,python-2.7,Python 2.7,我想列出当前目录中目录名中带有“-”字符的目录。我使用了os.listdir(path)。这给了我错误: WindowsError:[错误123]文件名、目录名或卷 标签语法不正确: 非常感谢您提供的任何帮助用于获取目录内容,然后使用过滤器检查每个项目是否为目录: dirs_with_hyphen = [] for thing in os.listdir(os.getcwd()): if os.path.isdir(thing) and '-' in thing: dir

我想列出当前目录中目录名中带有“-”字符的目录。我使用了os.listdir(path)。这给了我错误:

WindowsError:[错误123]文件名、目录名或卷 标签语法不正确:

非常感谢您提供的任何帮助

用于获取目录内容,然后使用过滤器检查每个项目是否为目录:

dirs_with_hyphen = []
for thing in os.listdir(os.getcwd()):
    if os.path.isdir(thing) and '-' in thing:
        dirs_with_hyphen.append(thing)

print dirs_with_hyphen # or return, etc.
可以使用列表理解来缩短:

dirs_with_hyphen = [thing for thing in os.listdir(os.getcwd()) if os.path.isdir(thing) and '-' in thing]
我正在使用,但您可以传入表示文件夹的任何字符串


如果文件名不正确,则可能是转义不正确,或者它没有指向正确的文件夹(绝对路径与相对路径问题)。

我做了一些测试,成功地获得了错误。我不知道这是否是你为了得到错误而做的,因为没有提供任何例子

我所做的只是给出了一个无效的驱动器路径。不是一个可能有效且不存在的,而是一个总是错误的,例如,
'C:\'
'CC:\'
就是任何不是
'C:\'
的东西。至于你的问题

路径通常应如下所示,前缀为
r
,以忽略反斜杠作为转义字符或双反斜杠

import os

path = r"C:\Users\Steven\Documents\"
path = "C:\\Users\\Steven\\Documents\"

for file in os.listdir(path):
    if os.path.isdir(path+file) and '-' in file:
        print path + file

#List Comp
[path+file for file in os.listdir(path) if os.path.isdir(path+file) and '-' in file]

没有代码示例,回答起来有点困难。看见