开发者

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/SLI开发者_开发问答CE.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).

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("/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh")

If the directory was not empty, it will raise Directory not empty error. For that ruby have FiltUtils.rm_r method which will delete the directory no matter what!

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:

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. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜