lua文件操作(2)----文件转换

来源:互联网 发布:tcp 端口多连接 编辑:程序博客网 时间:2024/05/16 13:52

最近有空空闲  整理点东西吧

 

 

1.单个文件的转换

function filetofile(infile, outfile)local readfile = io.open(infile,"r")--读取文件assert(readfile)--打开时验证是否出错local writefile = io.open(outfile,"w")--写入文件(w覆盖)assert(writefile)--打开时验证是否出错local i=1for rline in readfile:lines() do--一行一行local tmp=string.gsub(rline, "^%s*(.-)%s*$", "%1")--去除首尾空格if 0~=string.len(tmp) then--不是空行if 1~=select(1, string.find(tmp, "#")) then--以#号开头的为注释writefile:write(i, tmp.."\n")--写入内容i=i+1endendendreadfile:close()writefile:close()end-------------------------------------------------filetofile("in.txt", "out.txt")

 

2.多个文件批量转换

以下几个函数是从网上修改的结果

 

--功能:获取路径下的文件路径名的集合--输入:当前路径,存放当前路径下所有的文件路径名table--输出:返回路径集合pathes(如:E:\Lua\module.lua 等)function getpathes(rootpath, pathes)    local pathes = pathes or {}    for entry in lfs.dir(rootpath) do        if entry ~= '.' and entry ~= '..' then            local path = rootpath .. '\\' .. entry            local attr = lfs.attributes(path)            assert(type(attr) == 'table')            if attr.mode == 'directory' then                --getpathes(path, pathes)  --用于递归            else                table.insert(pathes, path)            end        end    end    return pathesend 
------------------------------------------------------------------------------------功能:获取文件名--输入:路径名--输出:返回文件名(包括文件名+后缀名)function getfilename(pathname)if nil~=string.find(pathname, "%.") then--查找是否有点号(.)return string.match(pathname, ".+\\([^\\]*%.%w+)$")endend

 

--功能:获取txt文件的文件名的集合--输入:路径名的集合--输出:txt文件的文件名的集合function gettxtname(pathes)local outfile={}for i, v in pairs(pathes) doif nil~=string.find(v, "%.") then--查找是否有点号(.)local filename=getfilename(v)--获取文件名if "txt"==getextension(filename) then--获取扩展名为txt的文件名字table.insert(outfile, filename)endendendreturn outfileend

 

------------------------------------------------功能:获取扩展名--输入:文件名--输出:返回文件扩展名(如:txt)function getextension(filename)if nil~=string.find(filename, "%.") then--查找是否有点号(.)return filename:match(".+%.(%w+)$")endreturn nilend

注: 要包含   require "lfs"

function main()local s=lfs.currentdir() --获取当前路径local pathes={} --存放路径名的集合local outfile={} --输出的名字的集合getpathes(s, pathes)    --获取路径下的文件路径名的集合outfile=gettxtname(pathes)  --获取txt文件的文件名的集合--对当前目录下所有的.txt文件进行操作for i,v in pairs(outfile) doreadfile = io.open(v,"r")--读取文件assert(readfile)--打开时验证是否出错writefile = io.open("copy_"..v,"w")--写入文件assert(writefile)--打开时验证是否出错for rline in readfile:lines() do--一行一行读取非字段名local tmp=string.gsub(rline, "^%s*(.-)%s*$", "%1")--去除首尾空格if 0~=string.len(tmp) then--不是空行if 1~=select(1, string.find(tmp, "#")) then--以#号开头的为注释writefile:write(tmp.."\n")--写入内容endendendreadfile:close()--调用结束后记得关闭writefile:close()--调用结束后记得关闭endend-------------------------------------------------main()



 

 

原创粉丝点击