我的cloud9工作区在名为' onetwo'
的文件夹中有一个.csv文件和一个Ruby脚本这是Ruby脚本:
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
一切正常,直到最后一行(db被创建,表也是如此)。这是我得到的信息:
ERROR: could not open file "workspace/onetwo/jr_data_engineer_assignment.csv" for reading: No such file or directory (PG::UndefinedFile)
如果我尝试将文件路径指定为" jr_data_engineer_assignment.csv"我会得到同样的错误。或作为" /jr_data_engineer_assignment.csv"或作为" ./ jr_data_engineer_assignment.csv"。写文件路径的正确方法是什么?感谢。
答案 0 :(得分:0)
要继续@ archon92所说的,你可以使用File.expand_path(__dir__)
来获取运行脚本的目录的绝对路径。如果csv文件是相对于脚本的,你可以这样做:
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