求助:怎样追加内容到文本文件开头?

y4h3z4 1月前 234

io.open(filePath, "a+")是追加内容在文件末尾,怎样追加内容在文件开头?用io.open(filePath, "r+")出现乱码了。


Code AardioLine:16复制
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
    • try{
    • if (io.exist(filePath)){
    • var logFile = io.open(filePath, "a+");
    • logFile.write(tostring(tm) + "--" + 新内容 + '\n');
    • logFile.close();
    • }
    • else{// 文件不存在则直接写入新内容
    • var logFile = io.open(filePath,"w");
    • logFile.write(newContent);
    • logFile.close();
    • }
    • 运行记录内容=新内容;
    • }
    • catch(e){
    • if(logFile) {logFile.close();}
    • }


    最新回复 (4)
    • lcj21 1月前
      0 2
      Code AardioLine:19复制
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
    • 11.
    • 12.
    • 13.
    • 14.
    • 15.
    • 16.
    • 17.
    • 18.
    • 19.
      • import win;
      • // 定义文件路径
      • var filePath = "/test.txt"
      • // 读取原文件内容
      • var file = io.open(filePath, "r")
      • var oldContent = file.readAll()
      • file.close()
      • // 要插入到开头的新内容
      • var newContent = '这是插入到开头的内容\n'
      • // 合并内容并覆盖写入
      • file = io.open(filePath, "w")
      • file.write(newContent + oldContent)
      • file.close()
      • // 提示完成
      • win.msgbox("内容已追加到文件开头!")


    • y4h3z4 1月前
      0 3
      成功实现了,非常感谢!
    • 山海师 1月前
      0 4

      这样也行

      Code AardioLine:4复制
    • 1.
    • 2.
    • 3.
    • 4.
      • var f = io.open("/test.txt", "r+")
      • f.seek("set")
      • f.write("开始")
      • f.close()


    • y4h3z4 1月前
      0 5
      f.seek("set")是什么意思呢?好像不行
    返回