Lua - 在 txt 文件中插入或删除字符串

5 lua

假设我有一个包含字符串的 .txt 文件。如何删除某些字符,或在它们之间插入其他字符?示例:.txt 文件包含“HelloWorld”,我想在“Hello”后面插入一个逗号,然后在后面插入一个空格。我只知道如何从头开始写入并附加文件

local file = io.open("example.txt", "w")
file:write("Example")
file.close()
Run Code Online (Sandbox Code Playgroud)

小智 5

您需要将其分解为不同的步骤。

以下示例将“HelloWorld”替换为“Hello, World”

 --
 --  Read the file
 --
 local f = io.open("example.txt", "r")
 local content = f:read("*all")
 f:close()

 --
 -- Edit the string
 --
 content = string.gsub(content, "Hello", "Hello, ")

 --
 -- Write it out
 --
 local f = io.open("example.txt", "w")
 f:write(content)
 f:close()
Run Code Online (Sandbox Code Playgroud)

当然你需要添加错误测试等。

  • 如果你知道你不想让文件变得比当前更小,你也可以在打开文件时使用 `'r+'` 模式,而不是关闭和重新打开它,只需使用 `f:seek('set ')` 在 `f:read('*a')` 之后移回文件的开头并覆盖内容。这样做的好处是文件始终保持打开状态,并防止其他进程在读取文件和写入更新文件之间修改文件的竞争条件。 (2认同)