虽然LFS足够强大,但部分情况还是不能很好的适应,以下方法基本上都是以shell cmd的形式去执行,从而实现路径和文件操作的各种需要。
其实LFS和这里的方法结合起来,才是最后的
fileLib = {
--作用:替换~为用户路径字符串
explainUser=function(path)
local cmdstr = "echo "..path
local filepath = io.popen(cmdstr)
local real_path = filepath:read()
filepath:close()
return real_path
end;
--作用:创建文件夹
mkdirDeep=function(path)
os.execute("mkdir -p "..path)
end;
--作用:连续创建文件夹,一次性创建想要的文件夹
createFolder=function(path)
local path_tb={}
local new_path=""
-- 分割路径保存到table
for s in string.gmatch(path,"([^'/']+)") do
if s~=nil then
table.insert(path_tb,s)
end
end
-- 遍历并拼接路径检测是否存在,不存在则新建
for k,v in ipairs(path_tb) do
if k==1 then
new_path=v
else
new_path=new_path.."/"..v
end
if os.execute("cd "..new_path) then
else
os.execute("mkdir "..new_path)
end
end
end;
--作用:清楚文件夹下所有文件,连带删除文件夹
rmDeepPath=function(folderPath)
os.execute("rm -rf "..folderPath)
end;
--作用:删除空文件夹/文件
remove=function(folderPath)
os.remove(fileLib.explainUser(folderPath))
end;
--作用:获取某个文件夹下所有的文件
getAllFileInFolder=function(folderPath,backupPath)
local file_tb={}
local fileList={};
local newPath=""
local f=io.open(backupPath.."/file.txt",'a')
fileList=fileLib.getFileList(folderPath)
for i= 1, #fileList do
if string.find(fileList[i],"%.")==nil then
newPath=folderPath.."/"..fileList[i];
fileLib.getAllFileInFolder(newPath,backupPath)
else
f:write(folderPath.."/"..fileList[i].."\n")
end
end
f:close();
end;
--作用:获取文件夹下的一级文件及文件夹table
lsPath=function(path)
if fileLib.isPathExist(path) then
local a = io.popen("ls "..path.."/");
local fileTable = {};
if a==nil then
else
for eachFile in a:lines() do
table.insert(fileTable,eachFile)
end
end
return fileTable
end
return nil
end;
--作用:判断文件是否存在
isPathExist=function(path)
local f=io.open(fileLib.explainUser(path),"r")
return f~=nil and f:close();
end;
--是否为文件夹
isFolderExist=function(path)
os.execute("cd "..path)
end
}
local ft = fileLib.isFolderExist("~/tmp/a.py")
if ft == nil then
print("path do not exist")
else
for i, v in ipairs(ft) do
print(v)
end
end