Lua获取指定文件指定行的内容及向指定文件写入内容

一、读取指定文件指定行的内容

 1. 读取方法

--1.获取指定文件的指定行内容,若未指定行数,返回 {文件内容列表,文件总行数}
--2.若行数在文件总行数范围,返回 {文件内容列表,文件总行数,指定行数的内容}
--3.若行数超出文件总行数,返回 {文件内容列表,文件总行数}
--4.filePath:文件路径,rowNumber:指定行数
function  readTextRow(filePath, rowNumber)
    local openFile = io.open(filePath, "r")
    assert(openFile, "read file is nil")
    local reTable = {}
    local reIndex = 0
    for r in openFile:lines() do
        reIndex = reIndex + 1
        reTable[reIndex] = r
    end
    io.close(openFile)
    if rowNumber ~= nil and reIndex > rowNumber then
        return reTable, reIndex, reTable[rowNumber]
    else
        return reTable, reIndex
    end
end

 2. 读取示例

local thisTable, thisLen, thisText = readTextRow("test.txt", 1)
print(string.format("This Text last RowContent is %s\nThis Text Row is %s", thisTable[thisLen], thisLen))  --输出 最后一行内容 和 总行数
print("This first row content is "..thisText)   --输出 第一行内容

3. 示例文本内容如下:

 4. 输出内容如下:

 

 

二、指定文本写入内容,下面示例使用读取方法如上 ↑↑↑

1. 写入方法

--1.指定文件【追加 / 覆盖】写入【字符串 / 列表】内容
--2.wContent 的值可以时列表,也可以时字符串
--3.当 operatType = nil 或 0 时为追加写入,= 1 时为覆盖写入
function writeText(filePath, wContent, operatType)
    local openFile
    if operatType == 0 or not operatType then
        openFile = io.open(filePath, "a")
    elseif operatType == 1 then
        openFile = io.open(filePath, "w")
    end
    assert(openFile, "write file is nil")
    io.output(openFile)
    if type(wContent) == "table" then
        for wc in listIterator(wContent) do
            io.write(wc.."\n")
        end
    else
        io.write(wContent.."\n")
    end
    io.close(openFile)
end

2. 示例

print("")print("")
print("add write content list as follows")
local testArr = {"1", "2", "6"}
writeText("test.txt", testArr)                            --附加写入列表【多行】内容
local thisTable, thisLen = readTextRow("test.txt")        --获取指定文件【内容列表, 总行数】
print(string.format("This Text last RowContent is %s\nThis Text Row is %s", thisTable[thisLen], thisLen))  --输出最后一行内容和总行数
print("")print("")
print("add write content list as follows")
writeText("test.txt", "666")                              --附加写入一行内容 
local thisTable, thisLen = readTextRow("test.txt")
print(string.format("This Text last RowContent is %s\nThis Text Row is %s", thisTable[thisLen], thisLen))
print("")print("")
print("cover write content as follows")
writeText("test.txt", "000", 1)
local thisTable, thisLen = readTextRow("test.txt")         --覆盖写入一行内容,删除原有内容,需覆盖写入多行方式同上
print(string.format("This Text last RowContent is %s\nThis Text Row is %s", thisTable[thisLen], thisLen))

3. 示例输出结果如下

 

posted @ 2022-05-23 15:40  青丝·旅人  阅读(3692)  评论(0编辑  收藏  举报