gpt4 book ai didi

ruby - 在 Ruby 中使用 '+' 文件 IO 模式替换文件中的一行

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

这里是 Ruby 初学者!

我知道 Ruby 的 File.open 方法具有某些模式,例如 r,w,a,r+,w+,a+ 和互补的 b。我完全理解 r、w 和 a 模式的使用。但我似乎无法理解如何使用带有“+”符号的那些。任何人都可以为我提供一些链接,其中有示例以及使用它的解释吗?

它可以用来读取一行并用等量的内容就地编辑/替换它吗?如果是,那又如何?

示例数据文件:a.txt

aaa
bbb
ccc
ddd

演示.rb

file = File.open "a.txt","r+"
file.each do |line|
line = line.chomp
if(line=="bbb")then
file.puts "big"
end
end
file.close

我正在尝试用“big”替换“bbb”,但我得到了这个:-在 Notepad++ 中

aaa
bbb
big

ddd

在记事本中

aaa
bbb
bigddd

最佳答案

这个文档是从另一个答案里拿来的,所以不是我的,解决方案是我的

r  Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode. 
r+ Read-write mode. The file pointer will be at the beginning of the file.
w Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+ Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a Write-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+ Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

编辑:这里是你的样本的解决方案,大部分时间整个字符串被 gsubbed 并写回文件但是'infile'替换而不重写整个文件也是可能的您应该谨慎替换为相同长度的字符串。

File.open('a.txt', 'r+') do |file|
file.each_line do |line|
if (line=~/bbb/)
file.seek(-line.length-3, IO::SEEK_CUR)
file.write 'big'
end
end
end

=>
aaa
big
ccc
ddd

这是一种更传统的方式,尽管比大多数其他解决方案更简洁

File.open(filename = "a.txt", "r+") { |file| file << File.read(filename).gsub(/bbb/,"big") } 

EDIT2:我现在意识到这还可以更短

File.write(f = "a.txt", File.read(f).gsub(/bbb/,"big"))

关于ruby - 在 Ruby 中使用 '+' 文件 IO 模式替换文件中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10171714/

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