Ruby Net :: FTP gettextfile无法在本地保存文件

时间:2012-06-23 10:12:59

标签: ruby net-ftp

我正在尝试从ftp站点检索文件(.csv)并将它们全部保存在同一文件夹中。我的代码如下所示:

#! /usr/bin/ruby

require 'logger'
require 'fileutils'
require 'net/ftp'
require 'rubygems'
require 'mysql2'
require 'roo'
require 'date'

# logging setup
log = Logger.new("/path_to_logs/ftp_log.log", 10, 1024000)
log.level = Logger::INFO

export_ftp_path = '/Receive/results/'
export_work_path ='/Users/pierce/results_exports/'

Net::FTP.open('host', 'username', 'password') do |ftp|
    log.info("Logged into FTP")
    ftp.passive = true
    ftp.chdir("#{export_ftp_path}")
      ftp.list.each do |file|
        log.info("Found file #{file}")
        new_file = file[56..115]  #take part of the file name and remove spaces and periods
        new_file = new_file.gsub(/[.]+/, "") 
        new_file = new_file.gsub(/\s/, "0") 
        ftp.gettextfile(file,"#{new_file}")
        log.info("Downloaded file #{new_file}")
      end
end

这是我收到的错误:

/Users/pierce/.rbenv/versions/1.9.2-p290/lib/ruby/1.9.1/net/ftp.rb:560:in `initialize': No such file or directory -  (Errno::ENOENT)
    from /Users/pierce/.rbenv/versions/1.9.2-p290/lib/ruby/1.9.1/net/ftp.rb:560:in `open'
    from /Users/pierce/.rbenv/versions/1.9.2-p290/lib/ruby/1.9.1/net/ftp.rb:560:in `gettextfile'
    from ftp_test.rb:44:in `block (2 levels) in <main>'
    from ftp_test.rb:33:in `each'
    from ftp_test.rb:33:in `block in <main>'
    from /Users/pierce/.rbenv/versions/1.9.2-p290/lib/ruby/1.9.1/net/ftp.rb:116:in `open'

正如所建议的,这里是我对puts文件的值,并放置new_file。

file = -rwxr-xr-x    1 1130419  114727       9546 May 17 08:11 results_Wed. 16 May 2012.csv
new_file = results_Wed0230May02012csv

有关在gettextfile或我的脚本中更改内容以正确保存文件的任何建议吗?

1 个答案:

答案 0 :(得分:1)

当您只需要目录中的文件列表时,应该使用nlst而不是listlist的输出需要正确解析。

当您请求文件时,它必须是原始文件名,包括所有空格。保存文件时,它可以是您想要的任何内容(包括空格或不包含空格)。该错误是因为您请求了错误的文件。请改用您的案例nlst。它会使它变得更容易(不需要转换或解析)。