我是一個python新手,我給了一個任務,不斷進入一個目錄并獲取一個空的子目錄或一個文件。如果目錄為空,則應將路徑寫入文件夾.txt,如果目錄中有文件,則應寫入該文件的路徑。例如:目錄 a 包含:a/apple/mango/ess.txta/gat.xmla/apple/asl/cdr/opa/est.pya/apple/dse/a/dews輸出(文件夾.txt)文件應為 :a/apple/dse/a/dews輸出(文件.txt)文件應為:a/apple/mango/ess.txta/gat.xma/apple/asl/cdr/opa/est.py我嘗試使用這個邏輯: for subdir, dirs, files in os.walk(path): for files in dirs: fp1 = (os.path.join(path, files)) print (fp1) if len(os.listdir(fp1)) == 0: print("Directory is empty") folder_added.write("\n Empty folder found %s \n" % (fp1))但它只持續到兩個子文件夾。
1 回答

蝴蝶刀刀
TA貢獻1801條經驗 獲得超8個贊
您走在正確的軌道上。此循環的每次迭代都描述一個新目錄。在每個目錄中,您要首先檢查 列表是否為空。如果為空,則將目錄路徑(在下面的示例中)寫入文件。如果 不為空,您可以循環訪問它并將文件名寫入其他輸出文件:filesrootfiles
f_folders = open('folders.txt', 'w')
f_files = open('files.txt', 'w')
for root, dirs, files in os.walk('.'):
if not files:
# Empty directory
f_folders.write(root + '\n')
else:
for f in files:
fpath = os.path.join(root, f)
f_files.write(fpath + '\n')
添加回答
舉報
0/150
提交
取消