【问题标题】:why the function io.write() does not work in lua为什么函数 io.write() 在 lua 中不起作用
【发布时间】:2021-04-29 22:22:02
【问题描述】:

我想统计一个文本中单词的出现次数,并给出前十个单词及其出现次数。

我使用函数 io.open() 打开一个输入文件作为文件句柄,然后在文件句柄上做一些事情,把结果放在一个表中。然后关闭输入文件句柄。并打开一个输出文件,它是一个新文件,因为文件句柄尝试将结果写入该文件。但它不起作用。代码如下。

txt "ioinput.txt" 是有文章的输入文件,txt "iooutput.txt" 是输出文件

input_file = io.open("ioinput.txt", r)

--[[
This block of code is to count the number of word,
which has been verified by the print function in the following.
--]]

input_file:close()

output_file = io.open("iooutput.txt", a)

local n = 10
for i = 1, n do
    output_file:write(words[i], "\t", counter[words[i]], "\n")
    --print(words[i], "\t", counter[words[i]], "\n")
end
output_file:flush()
output_file:close()

【问题讨论】:

  • 我假设您评论的打印显示循环正在执行并且数据是您所期望的?另外,当您说“不起作用”时,这是什么意思?文件是空白的吗?或者可能充满了胡言乱语?你有错误吗?
  • 我刚刚注意到io.open("iooutput.txt", a) 你有a 而不是"a" 这意味着你的第二个参数是nil 而默认是"r" 所以你处于读取模式,这就是为什么写不工作。 io.open("ioinput.txt", r) 同样是“错误”的,但它在这里“有效”,因为读取了默认模式。

标签: lua io


【解决方案1】:

请参考Lua 5.4 Reference Manual: io.open

io.open(文件名[,模式])

此函数以字符串模式中指定的模式打开一个文件。 如果成功,它会返回一个新的文件句柄。

模式字符串可以是以下任意一种:

"r": read mode (the default);
"w": write mode;
"a": append mode;
"r+": update mode, all previous data is preserved;
"w+": update mode, all previous data is erased;
"a+": append update mode, previous data is preserved, writing is only allowed at the end of file.

模式字符串的末尾也可以有一个'b',这是在 一些系统以二进制模式打开文件。

请注意,可选模式是以字符串形式提供的。

在您的代码中

input_file = io.open("ioinput.txt", r)output_file = io.open("ioinput.txt", a)

您的使用模式ra。两个零值。模式默认为"r",即读取模式。您无法写入以读取模式打开的文件。

【讨论】:

    猜你喜欢
    • 2018-12-28
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多