【问题标题】:Ruby on Rails: How do I move all files from one folder to another folder?Ruby on Rails:如何将所有文件从一个文件夹移动到另一个文件夹?
【发布时间】:2010-07-20 16:52:32
【问题描述】:

但我还需要一种方法来重命名它们以防发生冲突。

喜欢if exists? then file.name = "1-"+file.name 或者类似的东西

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    也许这样的东西适合你:

    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
    

    【讨论】:

      【解决方案2】:

      上面的代码有效,但小错误,您正在使用if File.exists?(file),它正在检查文件是否存在于原始文件夹/或子文件夹中,(这没有用,因为它已被读取,因为它已经存在)。您需要检查目标文件夹中是否已存在文件。由于这种语法,“else”永远不会被执行。所有文件都被命名为“1-filename”。 正确的是使用

      if File.exists? File.join(destination, File.basename(file))
      

      【讨论】:

        【解决方案3】:

        另一种选择是在 shell 中运行命令并处理响应:

        command = "mv *.* #{ new_directory }/"
        
        response = system command
        

        但是,处理现有文件名等是另一回事。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-01-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-12
          • 1970-01-01
          相关资源
          最近更新 更多