[QUESTION] Reading Text From TXT
-
A friend of mine is working on a script that generates a file for printing. He is interested in being able to add some user-supplied text from a TXT file. Would one of the gurus be so kind as to give an idea about how that is done so I can pass it on to him? Thanks in advance.
-
To read text from a file he needs to have the path to it as a string, he then needs to 'open' the file for reading and then read it and then close it.
If he is adding stuff into another file he should already be aware of several similar methods - so something like...
infile="C:/Temp/In.txt" return unless File.exist?(infile) fi=File.open(infile, "r") txt=fi.read fi.close outfile="C:/Temp/Out.txt" fo=File.open(outfile, "w") fo.puts("This is text read from '"+infile+"'") fo.puts(txt) fo.puts("That was text read from '"+infile+"'") fo.close
Of course the files' paths will vary!
He might already have the 'outfile' open to 'puts' into... -
Thank you very much, TIG. I'll pass that on to him.
-
I'd just write:
text = IO.read("path/to/file.txt")
Advertisement