I want to read the contents of a file and save it into a variable. Normally I would do something like:
text = File.read(filepath)
Unfortunately there's a file I'm working with that is encoded with UTF-16LE. I've been doing some research and it looks like I need to use File.Open instead and define the encoding. I read a suggestion somewhere that said to open the file and read in the data line by line:
text = File.open(filepath,"rb:UTF-16LE") { |file| file.lines }
However if I run:
puts text
I get:
#<Enumerator:0x23f76a8>
How can I read in the content of the UTF-16LE file into a variable?
Note: I am using Ruby 1.9.3 and a Windows OS
The lines
method is deprecated. If you expect text
to be an array with lines, then use readlines
.
text = File.open(filepath,"rb:UTF-16LE"){ |file| file.readlines }
As the Tin Man says, it's better practise to process each line seperately, if possible:
File.open("test.csv", "rb:UTF-16LE") do |file|
file.each do |line|
p line
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With