[英]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.