2015-11-26 47 views
-1

我想列出目录名称中具有“ - ”字符的当前目录中的目录。我用os.listdir(路径)。它给我的错误:在目录名称中列出具有“ - ”字符的目录

"WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:"

任何帮助,将不胜感激

+0

如果没有您的代码示例,有点难以回答。请参阅http://stackoverflow.com/help/mcve – pvg

回答

0

使用os.listdir获得目录内容,然后筛选使用os.path.isdir检查,如果每个项目是一个目录:

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] 

我正在使用os.getcwd,但您可以传入代表文件夹的任何字符串。

如果您收到关于文件名错误的错误信息,那么您可能无法正确转义,或者它没有指向正确的文件夹(绝对vs相对路径问题)。

0

我做了一些测试,我设法得到你的错误。我不知道这是你做了什么来获得错误,因为没有提供任何示例。

我虽然做了一个无效的驱动器路径。没有一个可能是有效的,不存在的,例如,总是错误的。 '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] 
相关问题