Get the file path to replace it with one that had a .csv extension

I had this small script that, once it checked the file was writable, would get the file path to replace it with one that had a .csv extension.

myarray = Sketchup.active_model.path.split('.')
status = myarray.delete_at(-1)
path = myarray[0]+tipo.to_s+'.csv'

I’ve encountered issues when the username contains a dot, so I would like to know if this would be the best option or if there is a simpler one.

model_path = Sketchup.active_model.path
directory = File.dirname(model_path)
filename_without_ext = File.basename(model_path, ".*")
new_extension = ".csv"
new_file_path = File.join(directory, "#{filename_without_ext}#{new_extension}")
1 Like

There is a standard library extension for this.


require 'pathname'

puts pn = Pathname.new(Sketchup.active_model.path).sub_ext('.csv')


Documentation can be found here.
https://ruby-doc.org/stdlib-2.7.2/libdoc/pathname/rdoc/index.html
https://docs.ruby-lang.org/en/3.2/Pathname.html

4 Likes

With just core Ruby and the API:

model = Sketchup.active_model
filename = model.title
unless filename.empty? # empty string if unsaved
  dir = File.dirname(model.path).gsub(/\\\\|\\/,'/')
  csv = File.join(dir, "#{filename}.csv")
end
3 Likes

Thanks @sWilliams and @DanRathbun . Both works perfectly.
It seems shorter to use the library.

You want 1 statement? Okay …

Sketchup.active_model.path.sub('.skp','.csv').gsub(/\\\\|\\/,'/')

… but it does not verify that the model has previously been saved. The result of this statement will be an empty string if the model has never been saved.

2 Likes

I test previously if the file has been saved and if it’s writable. I had problems in the past with read only files

1 Like

Other method…

def csv_path( model = Sketchup.active_model )
  m_path = model.path
  if m_path == ""
    UI.messagebox("Model must be saved before ... ")
    nil
  else
    m_path.slice!(-4..-1)
    m_path<<".csv"
  end
end
1 Like