Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read from a file in the same directory?

Tags:

ruby

I'm very much a beginner. I'd like to learn to read and write a file. Here's what I'm trying.

rdfile = File.open('bhaarat.txt', 'r+')

Unfortunately, this is returning "C:/directoriesblahblah/ubuntu3.rb:1:in 'initialize': No such file or directory - bhaarat.txt (Errno::ENOENT)

I have found solutions but I am not only new to Ruby but new to programming in general so I couldn't get an answer that made sense to me out of those.

Thanks in advance!

like image 445
vheissu Avatar asked Oct 11 '12 04:10

vheissu


1 Answers

To obtain the path to the current file, you can use:

__FILE__

To obtain the directory in which the current file exists, you can use:

File.dirname(__FILE__)

To create a path from strings, you can use:

File.join('part1', 'part2', ...)

Therefore, to create a path to a file in that directory, you can use:

File.join(File.dirname(__FILE__), 'filename')

If your file name is bhaarat.txt, the above becomes:

File.join(File.dirname(__FILE__), 'bhaarat.txt')

If you replace that in your code, you will get:

rdfile = File.open(File.join(File.dirname(__FILE__), 'bhaarat.txt'), 'r+')

You can also make this a separate variable, if you want, to make the code more readable:

path = File.join(File.dirname(__FILE__), 'bhaarat.txt')
rdfile = File.open(path, 'r+')
like image 192
rid Avatar answered Oct 24 '22 17:10

rid