简体   繁体   中英

How to delete files and folders but keep directory structure and leave behind a empty file instead of file itself?

I want to delete files and folders but leave directory structure intact.

But also I need to keep name of files in their current path. Something like, leaving behind a empty text with same name of file instead of that file itself.

My drive format is NTFS.

In Bash 4+ you can do the following to zero out all the files under a certain path:

shopt -s globstar
for file in /mnt/c/path/to/clean/**; do
    [[ -f $file ]] && : > "$file"
done

You can use os.walk to browse your directory structure and remplace each file with an empty one (overwrite the file:

import io
import os

work_dir = '.'
for root, dirnames, filenames in os.walk(work_dir):
    for filename in filenames:
        path = os.path.join(root, filename)
        io.open(path, mode='w').close()

See the documentation: https://docs.python.org/3/library/os.html

For a windows cmd solution

for /r "x:\path\to\clean" %a in (*) do ">%a" type nul

To run it from a batch file, percent signs need to be escaped (doubling them)

for /r "x:\path\to\clean" %%a in (*) do ">%%a" type nul

In Windows , you might want to use the robocopy command :

rem // Create copy with zero-length files at temporary location:
robocopy "\path\to\your\dir" "\path\to\temp\dir" *.* /E /CREATE
rem // Move tree at temporary location onto original location:
robocopy "\path\to\temp\dir" "\path\to\your\dir" *.* /E /MOVE /IS

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