简体   繁体   English

Python-如何在不更改其结构的情况下删除复杂文件夹中的内容?

[英]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? 是否有内置命令,或者我必须使用os.listdir为此编写一些递归函数?

Shamelessly stolen from the Python Documentation on Files and Directories with the removal of directories omitted: 从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))

See os.walk : 参见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.

相关问题 zip 包含所有内容的文件夹,但不保留 Python 中的目录结构 - zip a folder with all its content without preserving directory structure in Python Python移动和覆盖文件夹而不删除目标文件夹内容 - Python move and overwrite folder without delete destination folder content 如何使用boto3删除AWS桶中的文件夹及其内容 - How to delete folder and its content in a AWS bucket using boto3 如何在python中做一个复杂的过滤器 - How to do a complicated filter in python 如何在不删除文件夹的情况下删除文件夹中的内容 python - How to delete the contents within a folder without deleting the folder using python 如何使用 Python 删除 Amazon S3 上的文件夹及其内容 - How to delete a folder and its contents on Amazon S3 using Python 在Python 2中,如何在不更改其回溯的情况下引发Python错误? - In Python 2, How to raise a Python error without changing its traceback? 如何使用不带“ Content-Length:0”的Python请求模块执行HTTP DELETE请求? - How to do a HTTP DELETE request with Python requests module without “Content-Length: 0”? 如何在不更改列表内容的情况下复制列表? - How do I make a copy of a list without changing its contents? 如何在不更改 ctime 的情况下写入文件? - How do you write to a file without changing its ctime?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM