luaファイル操作(2)----ファイル変換

3421 ワード

最近暇な時に整理しておきましょう.
 
 
1.単一ファイルの変換
function filetofile(infile, outfile)
	local readfile = io.open(infile,"r")	--    
	assert(readfile)						--         
	local writefile = io.open(outfile,"w")	--    (w  )
	assert(writefile)						--         

	local i=1
	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(i, tmp.."
") -- i=i+1 end end end readfile: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 pathes
end
 
----------------------------------------------------------------------------------
--  :     
--  :   
--  :     (     +   )
function getfilename(pathname)
	if nil~=string.find(pathname, "%.") then	--       (.)
		return string.match(pathname, ".+\\([^\\]*%.%w+)$")
	end
end

 
--  :  txt         
--  :      
--  :txt         
function gettxtname(pathes)
	local outfile={}
	for i, v in pairs(pathes) do
		if nil~=string.find(v, "%.") then						--       (.)
			local filename=getfilename(v)						--     
			if "txt"==getextension(filename) then				--      txt     
				table.insert(outfile, filename)
			end
		end
	end
	return outfile
end

 
----------------------------------------------
--  :     
--  :   
--  :       ( :txt)
function getextension(filename)
	if nil~=string.find(filename, "%.") then	--       (.)
		return filename:match(".+%.(%w+)$")
	end
	return nil
end

注意: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) do
		readfile = 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.."
") -- end end end readfile:close() -- writefile:close() -- end end ------------------------------------------------- main()