Walk a directory and remove files/directories

I copied a (presumably large) number of files on to an existing directory, and I need to reverse the action. The targeted directory contains a number of other files, that I need to keep there, which makes it impossible to simply remove all files from the directory. I was able to do it with Python. Here’s the script:

import os, sys, shutil

source = "/tmp/test/source" 
target = "/tmp/test/target" 


for root, dirs, files in os.walk(source): # for files and directories in source
    for dir in dirs:
        if dir.startswith("."):
            print(f"Removing Hidden Directory: {dir}")
        else: 
            print(f"Removing Directory: {dir}")
        try:
            shutil.rmtree(f"{target}/{dir}") # remove directories and sub-directories
        except FileNotFoundError:
            pass

    for file in files:
        if file.startswith("."): # if filename starts with a dot, it's a hidden file
            print(f"Removing Hidden File: {file}")
        else:
            print(f"Removing File: {file}")
        try:
            os.remove(f"{target}/{file}") # remove files        
        except FileNotFoundError:
            pass

print("Done")

The script above looks in the original (source) directory and lists those files. Then it looks into the directory you copied the files to(target), and removes only the listed files, as they exist in the source directory.

How can I do the same thing in Golang ? I tried to use filepath.WalkDir(), but as stated in the docs:

WalkDir walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.

If WalkDir() includes the root, then os.Remove or os.RemoveAll will delete the whole thing.

Got the answer. Use os.ReadDir to read source the directory entries. For each entry, os.RemoveAll the corresponding target file.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.