Hrablicky
Hrablicky

Reputation: 143

Lua need to read the file, which I just wrote in same program

Need to write some file, then open it for reading and write some lines to another file - all this in one script. My problem is, that I:

  1. open file1 in read mode (file1=io.open("my_file.txt","r"))

  2. open file2 in write mode (file2=io.open("my_changed_file.txt","w"))

  3. write the changed content from file1 to file2

  4. open the file2 (tried also open as file3=io.open("my_changed_file.txt","r")) in read mode and print some lines from it for example

I tried several ways, like file2:flush(), or file2:close() and re-open after I finished writing, but it always returns nil when I want to print some lines

file1=io.open("my_file.txt","r")
file2=io.open("my_changed_file.txt","w")

for line in file1:lines() do
   file2:write(line.."changes")
end

file2:flush()
file3=io.open("my_changed_file.txt","r")
--write several lines to another file or something 
--(need to combine changed lanes from file2 and original lines from file1 based on my key)

Upvotes: 2

Views: 362

Answers (1)

Paul Kulchenko
Paul Kulchenko

Reputation: 26774

I've tried your script with minor changes in Lua 5.1, 5.2, and 5.3 and it works as expected in all those versions. My script is below and there is one change that may be important: write doesn't add a new line as print does, so you may need to add it yourself if you want the output to be on different lines:

local file1=io.open("my_file.txt","r")
local file2=io.open("my_changed_file.txt","w")
for line in file1:lines() do
   file2:write(line.."changes\n")
end
file2:close()
local file3=io.open("my_changed_file.txt","r")
print(file3)
for line in file3:lines() do print(line) end

Upvotes: 3

Related Questions