Lua常用的文件 *** 作

Lua常用的文件 *** 作,第1张

一、基本的文件读写 (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")

--创建名字为123的文件夹

os.execute("md 123")

--创建名字为123.txt 内容为456的文件

local file = io.open("123.txt","w")

file:write("456")

file:close()

file = io.open("c:\Files\xxx.txt", "w") 或者file = assert(io.open("c:\Files\xxx.txt", "w"))c:\Files\xxx.txt 代表路径 xxx 代表文件名 .txt 代表创建文件格式 逗号后面的参数 w 代表是 写入的意思,他会在这个文件夹中创建这个名字和格式的文件。第一个方法和第二个方法的区别是 第一个 会隐藏接收一个参数 显示错误信息第二个方法会在不成功的时候直接报错。


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

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

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

发表评论

登录后才能评论

评论列表(0条)

保存