Read the file contents as a string

what is wrong
does not read the file contents as a string

REDONDO 9.5.txt
K#4

f = File.open “/ruby/REDONDO 9.5.txt”, "r"
arr = f.readline
f.close
puts arr
kk = arr

componame = kk
compo = Sketchup.active_model.definitions[componame]
if compo
model = Sketchup.active_model
def_list = model.definitions
ents = model.entities
inst1 = ents.add_instance compo, [0, 0, 0]
else
puts "#{componame} does NOT exist!"
end

@janunes

Windows or mac?

For one thing, you need to provide the actual full path to the text file. Do you really have a /ruby directory on your root filesystem?

1 Like

Did you check the Ruby console when you ran that code? It should contain error messages about the problem (which, as Jim says, is very likely that no such file exists at the given path).

1 Like

Can you elaborate on what you are seeing? If you are not seeing a string - what do you see instead?

Sidenote, prefer the block notation when opening files such that you ensure it’s closed even if you run into errors.

File.open(filename, 'r') { |file|
  file.readline
}

If you want to read the whole content you can use content = File.read(filename)

(When posting code, it’d help if you formatted the code as Preformatted Text - makes it much easier to read your code.)

2 Likes

Also remember that if you do fix your code… and you do get a reference to a line of text from that oddly located file, then it might contain the name of the component, but with a newline character at the end… e.g.
"compo_name\n"
So you should do a .chomp! to remove that…
Otherwise it’ll not be the exact same name you’re expecting…
AND of course all of this presupposes that this named component is already loaded into the model.definitions ??

You could give more details, to get better help…

1 Like

thank tig
rather the component already exists in the file,
when creating the first time.
Then I want him to repeat the same component with the same name several times reading the name in txt file that contains the name .

this solved my problem. thank you so much
Mr. Tig