0

My cloud9 workspace has a .csv file and a Ruby script in a folder called 'onetwo'

Here's the Ruby script:

require 'pg'

def create_db
  conn = PG.connect(dbname: 'postgres')
  conn.exec("CREATE DATABASE onetwo")
  conn = PG.connect(dbname: 'onetwo')
  conn.exec("CREATE TABLE orgs ( id INT, description VARCHAR, PRIMARY KEY (id) )")
  conn.exec("COPY orgs(id, description) FROM 'workspace/onetwo/jr_data_engineer_assignment.csv' DELIMITER ',' CSV HEADER")
end

Everything works fine until the last line (the db gets created and so does the table). Here's the message I get:

ERROR:  could not open file "workspace/onetwo/jr_data_engineer_assignment.csv" for reading: No such file or directory (PG::UndefinedFile)

I get the same error if I try to specify the file path as "jr_data_engineer_assignment.csv" or as "/jr_data_engineer_assignment.csv" or as "./jr_data_engineer_assignment.csv". What is the correct way to write the file path?? Thanks.

flpoirier
  • 41
  • 4
  • 1
    File paths usually work when you specify the files from root (absolute path) or from the context of present working directive(relative paths).Your path 'workspace/onetwo/jr_data_engineer_assignment.csv' does not seem to be from either.Try giving the file path from the root , atleast that should help you move ahead now even though its not recommended to hardcode paths for production! – archon92 May 22 '17 at 18:00

1 Answers1

0

To continue on what @archon92 stated, you can use File.expand_path(__dir__) to get the absolute path to the directory that script is running in. If the csv file is relative to the script, you could do:

require 'pg'

csv_file_path = File.expand_path('jr_data_engineer_assignment.csv')

def create_db
  conn = PG.connect(dbname: 'postgres')
  conn.exec("CREATE DATABASE onetwo")
  conn = PG.connect(dbname: 'onetwo')
  conn.exec("CREATE TABLE orgs ( id INT, description VARCHAR, PRIMARY KEY (id) )")
  conn.exec("COPY orgs(id, description) FROM '#{csv_file_path}' DELIMITER ',' CSV HEADER")
end
Donavan White
  • 1,126
  • 10
  • 23