简体   繁体   English

如何使用Dir类删除非空目录?

[英]How to delete a non-empty directory using the Dir class?

Dir.delete("/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh")  

causes this error: 导致此错误:

Directory not empty - /usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh 目录不为空 - /usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh

How to delete a directory even when it still contains files? 即使目录仍包含文件,如何删除目录?

Is not possible with Dir (except iterating through the directories yourself or using Dir.glob and deleting everything). Dir是不可能的(除了自己迭代目录或使用Dir.glob并删除所有内容)。

You should use 你应该用

require 'fileutils'
FileUtils.rm_r "/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh"

When you delete a directory with the Dir.delete , it will also search the subdirectories for files. 使用Dir.delete删除目录时,它还将在子目录中搜索文件。

Dir.delete("/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh")

If the directory was not empty, it will raise Directory not empty error. 如果目录不为空,则会引发Directory not empty错误。 For that ruby have FiltUtils.rm_r method which will delete the directory no matter what! 对于那个ruby有FiltUtils.rm_r方法,它将删除目录,无论如何!

require 'fileutils'
FileUtils.rm_r "/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh"

I use bash directly with the system(*args) command like this: 我直接使用bash system(*args)命令,如下所示:

folder = "~/Downloads/remove/this/non/empty/folder"
system("rm -r #{folder}")

It is not really ruby specific but since bash is simpler in this case I use this frequently to cleanup temporary folders and files. 它不是特定于ruby,但由于bash在这种情况下更简单,我经常使用它来清理临时文件夹和文件。 The rm command just removes anything you give it and the -r flag tells it to remove files recursively in case the folder is not empty. rm命令只删除你给它的任何东西, -r标志告诉它在文件夹不为空的情况下递归删除文件。

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

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