我想從一個列表中的元素傳遞給一個for循環,當然我得到的經典錯誤「參數1必須是一個字符串不把」 - 爲os.chdir()功能。傳遞列表元素的for循環
這裏是我的代碼,有什麼建議,我怎麼能找到解決上述錯誤,仍然通過我的列表中的元素到腳本的其餘部分,以便它遍歷每個人將不勝感激!
path= ['C:\\DataDownload\Administrative', 'C:\\DataDownload\Cadastral', 'C:\\DataDownload\Development']
for x in path[:]:
os.chdir(path)
#Remove all previous files from the current folder
for file in os.listdir(path):
basename=os.path.basename(file)
if basename.endswith('.DXF'):
os.remove(file)
if basename.endswith('.dbf'):
os.remove(file)
if basename.endswith('.kmz'):
os.remove(file)
if basename.endswith('.prj'):
os.remove(file)
if basename.endswith('.sbn'):
os.remove(file)
if basename.endswith('.sbx'):
os.remove(file)
if basename.endswith('.shp'):
os.remove(file)
if basename.endswith('.shx'):
os.remove(file)
if basename.endswith('.zip'):
os.remove(file)
if basename.endswith('.xml'):
os.remove(file)
完全無關你的問題,它會使你的生活更容易,如果你使用的擴展數組:'一些推廣= [「.DXF」,「.DBF」,「名爲.kmz」,...,」 .XML 「]'。然後,你可以這樣做'如果有的話(圖(拉姆達分機:basename.endswith(EXT),擴展)):os.remove(文件)'或'只是在擴展分機:如果basename.endswith(EXT): os.remove(文件);打破' – 2010-07-12 17:47:03
感謝邁克爾 - 我已經將你的想法「擴展擴展」納入我的代碼 - 更有效率 - 一個偉大的學習對我來說! – Jay 2010-07-12 18:13:48
@邁克爾:'endswith'支持元組作爲輸入,因此你例如可以簡化:'如果basename.endswith(EXTS):鑑於os.remove(FNAME)','exts'是擴展的一個元組。 – SilentGhost 2010-07-12 18:37:52