Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Prepend Text To A File In Lua

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

Code

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"
)

Put text at the start a file with Lua