简体   繁体   中英

Python - how do delete content in a complicated folder without changing its structure?

I have a folder with sub-folders, each can contain more sub-folders and so on. I want to delete all the files in all of them, but keeping the directory structure the same. Is there a built-in command or I have to write some recursive function for this using os.listdir?

Shamelessly stolen from the Python Documentation on Files and Directories with the removal of directories omitted:

# 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))

See 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM