我想知道将文本写入文件(假设为text.txt
)时的最佳方法,可以始终在结尾添加换行符。当我使用追加文本的方式添加文本时,
file = io.open("test.txt", "a")
file:write("hello")
文件看起来是两倍的大小:
hellohello
但我希望它看起来像这样:
hello
hello
我想知道将文本写入文件(假设为text.txt
)时的最佳方法,可以始终在结尾添加换行符。当我使用追加文本的方式添加文本时,
file = io.open("test.txt", "a")
file:write("hello")
文件看起来是两倍的大小:
hellohello
但我希望它看起来像这样:
hello
hello
与print
不同的是,在调用io.write
时,换行符不会自动添加,您可以自己添加:
与print
不同的是,在调用io.write
时,换行符不会自动添加,您可以自己添加:
file:write("hello", "\n")
实现这一目标最简单的方法是每次调用write
方法时都包含一个换行符序列,例如:file:write("hello\n")
或者 file:write("hello", "\n")
。这样,像这样的脚本:
file = io.open(test.txt, "a")
file:write("hello", "\n")
file:write("hello", "\n")
hello
hello
然而,还有很多其他解决方案可供选择(其中一些比其他方案更为优雅)。例如,在Java中输出文本时,有特殊的方法,如BufferedWriter#newLine()
,以更加清晰的方式完成相同的操作。因此,如果您对实现此目标的其他方法感兴趣,建议您查阅Lua文档以获取类似的方法/解决方案。