![](/img/trans.png)
[英]How do I access one of my models from within a ruby script in the /lib/ folder in my Rails 3 app?
[英]Ruby on Rails: How do I move all files from one folder to another folder?
但是我还需要一种方法来重命名它们以防发生冲突。
比如if exists? then file.name = "1-"+file.name
if exists? then file.name = "1-"+file.name
或类似的东西
也许这样的事情对你有用:
origin = '/test_dir'
destination = '/another_test_dir'
Dir.glob(File.join(origin, '*')).each do |file|
if File.exists? File.join(destination, File.basename(file))
FileUtils.move file, File.join(destination, "1-#{File.basename(file)}")
else
FileUtils.move file, File.join(destination, File.basename(file))
end
end
此致。
上面的代码有效,但有点错误,您正在使用if File.exists?(file)
,它正在检查文件是否存在于原始文件夹/或子文件夹中,(这是没有用的,因为它已被读取,因为它已经存在)。 您需要检查文件是否已存在于目标文件夹中。 由于这种语法,“else”永远不会被执行。 并且所有文件都被命名为“1-filename”。 正确的是使用
if File.exists? File.join(destination, File.basename(file))
另一种选择是在 shell 中运行命令并处理响应:
command = "mv *.* #{ new_directory }/"
response = system command
然而,处理现有文件名等是另一回事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.