0

A simple question. I have 1 file test.txt in userPath().."/log/test.txt with 15 line I wish read first line and remove first line and finally file test.txt with 14 line

Vinni Marcon
  • 606
  • 1
  • 4
  • 18
  • Did you look at other similar questions on stackoverflow to see if the anwsers worked for you? Like this question https://stackoverflow.com/questions/11201262/how-to-read-data-from-a-file-in-lua – Nifim Aug 24 '20 at 17:25

1 Answers1

0

local iFile = 'the\\path\\test.txt'

local contentRead = {}
local i = 1

file = io.open(iFile, 'r')

for lines in file:lines() do
    if i ~= 1 then
        table.insert(contentRead, lines)
    else
        i = i + 1 -- this will prevent us from collecting the first line
        print(lines) -- just in case you want to display the first line before deleting it
    end
end

io.close(file)

local file = io.open(iFile, 'w')

for _,v in ipairs(contentRead) do
    file:write(v.."\n")
end

io.close(file)

there must be other ways to simplify this, but basically what I did in the code was:

  1. Open the file in reading mode, and store all lines of text except the first line in the table contentRead

  2. I opened the file again, but this time in Write mode, causing the entire contents of the file to be erased, and then, I rewrote all the contents stored in the table contentRead in the file.

Thus, the first line of the file was "deleted" and only the other 14 lines remained

Vinni Marcon
  • 606
  • 1
  • 4
  • 18