【问题标题】:How do I access the filename of the CSV file I just opened?如何访问我刚刚打开的 CSV 文件的文件名?
【发布时间】:2016-10-23 00:14:52
【问题描述】:

我有一个看起来像这样的方法:

def extract_websites
  websites = []
  csvs = Dir["#{@dir_name}/#{@state}/*.csv"]

  csvs.each do |csv|
    CSV.foreach(csv, headers: true) do |row|
      websites << row['Website']
    end
  end
  websites.uniq!
end

但我需要做的是对于每个打开的 CSV 文件,我想检测该文件的名称。

我该怎么做?

【问题讨论】:

    标签: ruby csv


    【解决方案1】:

    在您的示例中,变量 csv 包含 CSV 文件的路径。 该局部变量在其子块中可用,它向下共享其范围,但不向上共享。

    所以:

    def extract_websites
      websites = []
      csvs = Dir["#{@dir_name}/#{@state}/*.csv"]
    
      csvs.each do |csv|
        puts File.expand_path(csv) # show the full path for each csv file
        CSV.foreach(csv, headers: true) do |row|
          puts csv # shows unexpanded path for each row of a csv
          websites << row['Website']
        end
      end
      websites.uniq!
    end
    

    应该打印出每个 CSV 文件和每个 row 的路径。

    【讨论】:

      猜你喜欢
      • 2017-12-19
      • 1970-01-01
      • 2019-12-28
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 2022-10-14
      • 2014-06-10
      相关资源
      最近更新 更多