gpt4 book ai didi

ruby - 如何在文本文件中间插入一行?

转载 作者:数据小太阳 更新时间:2023-10-29 08:35:41 25 4
gpt4 key购买 nike

myFile.txt 包含

This is a sample file
This contains some data
End of file

我将创建一个内容字符串(动态地)并将数组写入文件

我尝试使用 r+ 模式,但它会覆盖现有内容

file = File.open('myFile.txt','r+')
myString = 'Dynamic content' # varies accordingly for each file based on file
while (line = @file.gets)
next unless line =~ /sample file/
@file.puts(myString)
break
end

但它导致 myFile.txt 包含

This is a sample file
Dynamic content
e data
End of file

我尝试使用 with a+ 模式,它附加到最后一个,因为附加模式添加到文件的最后

我试图将 myFile.txt 设为

This is a sample file
Dynamic content
This contains some data
End of file

在 ruby​​ 中还有其他方法/模式可以做到这一点吗?

最佳答案

将文件想象成一张纸。一旦你在上面写了一些东西,添加内容的唯一安全方法就是追加。你不能在不覆盖某些东西的情况下在纸中间写文本。

一般来说,这种插入是通过临时文件完成的。它是这样的:

  1. 打开源文件source以供阅读
  2. 创建一个新文件target用于写入
  3. source 读取直到插入点并将其写入 target
  4. 将您的新内容写入target
  5. 复制剩余的sourcetarget
  6. 关闭文件
  7. 删除/重命名来源
  8. target 重命名为 source 的名称。

关于ruby - 如何在文本文件中间插入一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44559946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com