Home

Prepend Text To A File In Lua

This is what I'm using to prepend text to a file from a Neovim Telescope extension.

lua
prepend_file = function(file_path, line)
	local tmp_path = file_path .. ".tmp"
	local file = io.open(file_path, 'r') 
	local tmp = io.open(tmp_path, 'a')
	tmp:write(line .. "\n")
	for line in file:lines() do
		tmp:write(line)
		tmp:write("\n")
	end
	file:close()
	tmp:close()
	os.remove(file_path)
	os.rename(tmp_path, file_path)
end

prepend_file(
	"path/to/file.txt",
	"this is a new line"
)

- This doesn't have any error checking in it. Could definitely use that.

~ fin ~