我想列出目錄名稱中具有「 - 」字符的當前目錄中的目錄。我用os.listdir(路徑)。它給我的錯誤:在目錄名稱中列出具有「 - 」字符的目錄
"WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:"
任何幫助,將不勝感激
我想列出目錄名稱中具有「 - 」字符的當前目錄中的目錄。我用os.listdir(路徑)。它給我的錯誤:在目錄名稱中列出具有「 - 」字符的目錄
"WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:"
任何幫助,將不勝感激
使用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相對路徑問題)。
我做了一些測試,我設法得到你的錯誤。我不知道這是你做了什麼來獲得錯誤,因爲沒有提供任何示例。
我雖然做了一個無效的驅動器路徑。沒有一個可能是有效的,不存在的,例如,總是錯誤的。 '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]
如果沒有您的代碼示例,有點難以回答。請參閱http://stackoverflow.com/help/mcve – pvg