美文网首页
Lua常用的文件操作

Lua常用的文件操作

作者: zzqlb | 来源:发表于2018-08-13 21:12 被阅读0次

一、基本的文件读写

(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")

相关文章

  • Lua常用的文件操作

    一、基本的文件读写 (1) io.open 功能:按指定的模式打开一个文件,成功则返回文件句柄,失败则返回nil+...

  • Lua使用实记(转)

    c调用lua堆栈常用操作------- ===================初级================...

  • Lua扩展

    lua作为配置文件使用 使用LUA API分析这个文件,并获取width和height table操作lua 5....

  • Mac shell使用技巧总结

    整理了常用的Mac使用技巧 1.文件操作 常用目录 资源库 目录 文件操作 选择操作 文件编辑 将文件转成 HTM...

  • python常用文件操作总结

    python 移动文件或文件夹操作。python中对文件、文件夹操作时经常用到的os模块和shutil模块常用方法...

  • 读写文件操作

    读文件 写文件 File类常用操作

  • CAA:常用文件操作

    CATIA CAA:常用文件操作

  • python 03文件操作

    文件打开操作 文件常用操作 文件指针需要注意的是,进行文件操作的时候是存在文件指针的 进阶操作--文件修改的两种操...

  • protoc-gen-lua 生成的lua文件遇到error:

    使用protoc-gen-lua生成的lua文件,由于源proto文件定义的字段过多,在运行生成的lua文件时遇到...

  • Mac shell使用技巧总结

    1.文件操作 常用目录 资源库 目录 文件操作 选择操作 文件编辑 将文件转成 HTML,支持格式包括 Text,...

网友评论

      本文标题:Lua常用的文件操作

      本文链接:https://www.haomeiwen.com/subject/axesyftx.html