Sitz Blogz
Sitz Blogz

Reputation: 1061

How to name output file with respect to input file?

I have about 100 input files which, after processing, generate more than 2000 output files. I would like to name the output files based on the names of the input file.

Here is the command I run:

Start cmd /k "G:Path\eachGeo.bat G:\Path\InputGeo\*.csv"

The input files are read via cmd by executing the .bat file. Output is stored at a different path:

outputfilename = 'Path\outputGeo\\' + Time.now.to_i.to_s + 
                 '_' + eachTag[45..54] + '_output.csv'

In the code above I am using Time.now.to_i.to_s to name the output files based on the current system time.

I would like to change this to be the name of the input file.

Upvotes: 0

Views: 401

Answers (1)

tadman
tadman

Reputation: 211540

Normally you'd tackle it like this where you're using things like File.basename to extract the relevant part of the original file path:

Dir.glob("path/*.csv") do |path|
  CSV.open(path) do |csv_in|
    # ...

    out_path = "output_path/%s_%s.csv" % [
       File.basename(path, ".csv"),
       each_tag[45..54]
    ]

    CSV.open(out_path, "w") do |csv_out|
      # ...
    end
  end
end

This is a really simple example. I'd avoid putting your output files in the same directory as the input ones so you don't mistakenly read them in again when you run the program a second time.

Upvotes: 1

Related Questions