在Lua中编写多行文本文件

16

我想知道将文本写入文件(假设为text.txt)时的最佳方法,可以始终在结尾添加换行符。当我使用追加文本的方式添加文本时,

file = io.open("test.txt", "a")
file:write("hello")

文件看起来是两倍的大小:

hellohello

但我希望它看起来像这样:

hello
hello
2个回答

15

print不同的是,在调用io.write时,换行符不会自动添加,您可以自己添加:

print不同的是,在调用io.write时,换行符不会自动添加,您可以自己添加:

file:write("hello", "\n")

5

实现这一目标最简单的方法是每次调用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文档以获取类似的方法/解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接