问题
I'm trying to remove non-empty directory in Lua but without success,
I tried the following:
os.remove(path_to_dir)
And got the error: Directory not empty 39
When 39 is the number of files in path_to_dir
Also tried:
require ('lfs')
lfs.rmdir(path_to_dir)
And got the error: Directory not empty'
Worth to mention that I did chmod -R a+rX *
to path_to_dir
Thanks for the help.
回答1:
You can either follow @EgorSkriptunoff's suggestion and use OS-specific commands to remove non-empty directories or get the list of files/sub-directories using lfs (for example, as described in this SO answer) and delete them one-by-one using os.remove
.
回答2:
With path library you can do
function rmdir(p)
path.each(path.join(p,"*"), function(P)
path.remove(P)
end,{
param = "f"; -- request full path
delay = true; -- use snapshot of directory
recurse = true; -- include subdirs
reverse = true; -- subdirs at first
})
path.remove(p)
end
回答3:
Depending on your os, you could just do this:
os.execute("rm --recursive " .. path_to_directory)
(this example is for linux)
回答4:
With lua lfs, you can implement a recursive function to do this.
local lfs = require('lfs')
local deletedir
deletedir = function(dir)
for file in lfs.dir(dir) do
local file_path = dir..'/'..file
if file ~= "." and file ~= ".." then
if lfs.attributes(file_path, 'mode') == 'file' then
os.remove(file_path)
print('remove file',file_path)
elseif lfs.attributes(file_path, 'mode') == 'directory' then
print('dir', file_path)
deletedir(file_path)
end
end
end
lfs.rmdir(dir)
print('remove dir',dir)
end
deletedir('tmp')
来源:https://stackoverflow.com/questions/37835565/lua-delete-non-empty-directory