How to Read Whole File in Ruby

How to read whole file in Ruby?


IO.read("filename")

or

File.read("filename")

What's a reasonable way to read an entire text file as a single string?

What about IO.read()?

Edit: IO.read(), as an added bonus, closes the file for you.

What are all the common ways to read a file in Ruby?


File.open("my/file/path", "r") do |f|
f.each_line do |line|
puts line
end
end
# File is closed automatically at end of block

It is also possible to explicitly close file after as above (pass a block to open closes it for you):

f = File.open("my/file/path", "r")
f.each_line do |line|
puts line
end
f.close

How to read lines of a file in Ruby

I believe my answer covers your new concerns about handling any type of line endings since both "\r\n" and "\r" are converted to Linux standard "\n" before parsing the lines.

To support the "\r" EOL character along with the regular "\n", and "\r\n" from Windows, here's what I would do:

line_num=0
text=File.open('xxx.txt').read
text.gsub!(/\r\n?/, "\n")
text.each_line do |line|
print "#{line_num += 1} #{line}"
end

Of course this could be a bad idea on very large files since it means loading the whole file into memory.

Reading a whole file in Ruby (possibly a bug)

Use File.binread to read binary data.

On certain operating systems (notably Windows), there is a difference between opening a file in "binary mode" (8-bit characters) and "text mode" (7-bit characters). Because of this, these IO implementations can do things like detect end-of-file when there is a zero character, or mangle up characters outside of the ASCII range if you don't tell them to expect binary data.

If you open a file in Ruby, using mode "rb" instead of "r" will tell the OS that you expect binary data, and if it cares about that, it will do the right thing. File.binread() opens the underlying file it will read from with that mode.

How to read a large file into a string

Marshal is a binary format, so you need to read and write in binary mode. The easiest way is to use IO.binread/write.

...
IO.binwrite('mat_save', mat_dump)
...
mat_dump = IO.binread('mat_save')
@mat = Marshal.load(mat_dump)

Remember that Marshaling is Ruby version dependent. It's only compatible under specific circumstances with other Ruby versions. So keep that in mind:

In normal use, marshaling can only load data written with the same major version number and an equal or lower minor version number.

[Ruby]IO.Read not reading the whole file

I finally found an other way to solve my problem with File.copy_stream().

But if someone knows why this doesn't work, feel free to explain to me.

How to open and read a file in one line in ruby


File.read("/path/to/file")

It will read whole file content and return it as a result.

Is there a way to seek through a file without loading the whole thing into an array?

For the purpose you can use the each_line iterator, combined with with_index to have the line number of the current line (counting from 0):

File.open('myfile') do |file|

file.each_line.with_index do |line, lineno|
case lineno
when 0
# line 1
when 21
# line 22
end
end

end

By using open, passing a block to it, instead of new, you are guaranteed that the file is properly closed at the end of the block execution.


Update The with_index method accepts an optional argument to specify the starting index to use, so che code above could be better written like this:

file.each_line.with_index(1) do |line, lineno|
case lineno
when 1
# line 1
end
end

How to read lines from file into array?

Do as below :

File.readlines('test.txt')

Read documentation :

arup@linux-wzza:~> ri IO::readlines

= IO::readlines

(from ruby site)
------------------------------------------------------------------------------
IO.readlines(name, sep=$/ [, open_args]) -> array
IO.readlines(name, limit [, open_args]) -> array
IO.readlines(name, sep, limit [, open_args]) -> array

------------------------------------------------------------------------------

Reads the entire file specified by name as individual lines, and
returns those lines in an array. Lines are separated by sep.

a = IO.readlines("testfile")
a[0] #=> "This is line one\n"

If the last argument is a hash, it's the keyword argument to open. See IO.read
for detail.

Example

arup@linux-wzza:~/Ruby> cat out.txt
name,age,location
Ram,12, UK
Jadu,11, USA
arup@linux-wzza:~/Ruby> ruby -e "p File::readlines('./out.txt')"
["name,age,location\n", "Ram,12, UK\n", "Jadu,11, USA\n"]
arup@linux-wzza:~/Ruby>


Related Topics



Leave a reply



Submit