lua怎么检测文件是否存在?谢谢

lua怎么检测文件是否存在?谢谢,第1张

只需要 open 一下。然后看看返回值。

somefile="xxxj.pdf"

local F,err=io.open(somefile,"r+")

print(err)

如果文件不存在 err 会包含相关信息。

一、基本的文件读写

(1) io.open

功能:按指定的模式打开一个文件,成功则返回文件句柄,失败则返回nil+错误信息

file = io.open (filename [, mode])

mode 的值有:

r  以只读方式打开文件,该文件必须存在。

w  打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。

a   以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。(EOF符保留)

r+  以可读写方式打开文件,该文件必须存在。

w+  打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。

a+   与a类似,但此文件可读可写

b   二进制模式,如果文件是二进制文件,可以加上b

+   号表示对文件既可以读也可以写

(2)  file:write(...)

功能:按指定的参数格式输出文件内容,参数必须为字符或数字,若要输出其它值,则需通过tostring或string.format进行转换

(3)  file:close()

功能:关闭文件,我抽U盘才懒得'安全删除硬件',一般都直接拔了.这个命令也一样,反正lua有垃圾自动回收........

(4) io.lines ([filename])

功能:打开指定的文件filename为读模式并返回一个迭代函数,每次调用将获得文件中的一行内容,当到文件尾时,将返回nil,并自动关闭文件

(5) io.popen ([prog [, mode]])

功能:开始程序prog于额外的进程,并返回用于prog的文件句柄(并不支持所有的系统平台)

二、常用文件 *** 作

(1)判断文件是否存在

function checkFileExist(path)

        local file = io.open(path, "rb")

        if file then file:close() end

        return file ~= nil

 end

(2)判断文件夹是否存在()

os.execute("cd "..dirPath)

返回值为0便是存在,不为0时表示不存在

(3)创建文件夹

os.execute("mkdir "..dirPath)

(4)删除文件

os.remove(filepath)

eg:创建多层文件夹

Configs.debugFilePath = "E:/test1/test2/test3/test4/test.txt"

function checkDirExist()

    local dirlist = string.split(Configs.debugFilePath,"/")

    local filenamelen = string.len(dirlist[#dirlist])

    local dirpath = string.sub(Configs.debugFilePath,1,string.len(Configs.debugFilePath)-filenamelen-1)

    local path_tb={}

    local new_path=""

    -- 分割路径保存到table

    for s in string.gmatch(dirpath,"([^'/']+)") 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) ~= 0 then

            os.execute("mkdir "..new_path)

        end

    end

end

(5)获得文件夹下的所有文件路径(windows)

io.popen("dir path /b /s")

eg:

local dirinfo= io.popen("dir path /b /s")

local all = dirinfo:read("*all")


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11738242.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存