![](/img/trans.png)
[英]zip a folder with all its content without preserving directory structure in Python
[英]Python - how do delete content in a complicated folder without changing its structure?
我有一個帶有子文件夾的文件夾,每個文件夾可以包含更多子文件夾,依此類推。 我想刪除所有文件中的所有文件,但保持目錄結構不變。 是否有內置命令,或者我必須使用os.listdir為此編寫一些遞歸函數?
從Python文檔文件和目錄中無恥地偷了東西,並刪除了目錄:
# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
參見os.walk
:
import os
top = '/some/dir'
for root, dirs, files in os.walk(top):
for name in files:
os.remove(os.path.join(root, name))
import os
#check if file is hidden
def is_hidden(filepath):
name = os.path.basename(os.path.abspath(filepath))
return name.startswith('.')
top = '/dir'
for root, dirs, files in os.walk(top):
for name in files:
#do not delete hidden files (as asked by OP in comments)
if is_hidden(name) == false:
os.remove(os.path.join(root, name))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.