简体   繁体   English

目录遍历和删除文件/目录

[英]Directory walk 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.我能够用 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 Go?我怎样才能在 Go 中做同样的事情? I tried filepath.WalkDir(), but as stated in the docs:我尝试了 filepath.WalkDir(),但如文档中所述:

WalkDir walks the file tree rooted at root, calling fn for each file or directory in the tree, including root. WalkDir 遍历以根为根的文件树,为树中的每个文件或目录调用 fn,包括根。

If WalkDir() includes the root, then os.Remove() or os.RemoveAll() will delete the whole thing.如果 WalkDir() 包含根,则 os.Remove() 或 os.RemoveAll() 将删除整个内容。

Answered by Cerise Limon .Cerise Limon回答。 Use os.ReadDir to read source the directory entries.使用 os.ReadDir 读取目录条目的源代码。 For each entry, os.RemoveAll the corresponding target file对于每个条目,os.RemoveAll 对应的目标文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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