擅长:python、mysql、java
<p>假设您想:</p>
<ul>
<li>删除给定根目录中的所有内容,禁止列出例外目录</li>
<li>删除每个例外目录中的所有内容</li>
</ul>
<p>然后像这样(未经测试!)脚本应该起作用:</p>
<pre><code>import sys, os, shutil
def prune(dirpath, exceptions=()):
for name in os.listdir(dirpath):
path = os.path.join(dirpath, name)
if name in exceptions:
prune(path)
else:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
exceptions = ('dir1', 'dir2', '.dotfile1', '.dotfile2', 'dir3', '.dotdir1')
if __name__ == '__main__':
root = os.path.join('/home', sys.argv[1], 'parentdir')
prune(root, exceptions)
</code></pre>