gpt4 book ai didi

ruby - 如何将文件内容复制到另一个文件?

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

虽然这看起来很基础,但我无法设法将一个文件的内容复制到另一个文件。到目前为止,这是我的代码:

#!/usr/bin/ruby

Dir.chdir( "/mnt/Shared/minecraft-server/plugins/Permissions" )

flist = Dir.glob( "*" )

flist.each do |mod|
mainperms = File::open( "AwesomeVille.yml" )
if mod == "AwesomeVille.yml"
puts "Shifting to next item..."
shift
else
File::open( mod, "w" ) do |newperms|
newperms << mainperms
end
end
puts "Updated #{ mod } with the contents of #{ mainperms }."
end

最佳答案

为什么要将一个文件的内容复制到另一个文件?为什么不使用操作系统来复制文件,或者使用 Ruby 的内置 FileUtils.copy_file

ri FileUtils.copy_file
FileUtils.copy_file

(from ruby core)
------------------------------------------------------------------------------
copy_file(src, dest, preserve = false, dereference = true)

------------------------------------------------------------------------------

Copies file contents of src to dest. Both of src and
dest must be a path name.

更灵活/更强大的替代方法是使用 Ruby 的内置 FileUtils.cp :

ri FileUtils.cp
FileUtils.cp

(from ruby core)
------------------------------------------------------------------------------
cp(src, dest, options = {})

------------------------------------------------------------------------------

Options: preserve noop verbose

Copies a file content src to dest. If dest is a
directory, copies src to dest/src.

If src is a list of files, then dest must be a directory.

FileUtils.cp 'eval.c', 'eval.c.org'
FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', :verbose => true
FileUtils.cp 'symlink', 'dest' # copy content, "dest" is not a symlink

关于ruby - 如何将文件内容复制到另一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6005498/

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