Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Tags:

ruby

I installed Ruby 1.9.2 on my Win 7 machine. Created a simple analyzer.rb file. It has this one line:

File.open("text.txt").each {|line| puts line}

When I run the code, it gives me this error:

analyzer.rb:1:in `initialize': No such file or directory - text.txt (Errno::ENOENT)
from analyzer.rb:1:in `open'
from analyzer.rb:1:in `<main>'
Exit code: 1

I don't get it. There is a text.txt file in the same directory as the analyzer.rb file. I also tried feeding the absolute path of the file, C:\Ruby192\text.txt, but no dice. What am I missing?

like image 233
Ege Ersoz Avatar asked Jul 04 '11 02:07

Ege Ersoz


3 Answers

Start by figuring out what your current working directory is for your running script.
Add this line at the beginning:

puts Dir.pwd.

This will tell you in which current working directory ruby is running your script. You will most likely see it's not where you assume it is. Then make sure you're specifying pathnames properly for windows. See the docs here how to properly format pathnames for windows:

http://www.ruby-doc.org/core/classes/IO.html

Then either use Dir.chdir to change the working directory to the place where text.txt is, or specify the absolute pathname to the file according to the instructions in the IO docs above. That SHOULD do it...

EDIT

Adding a 3rd solution which might be the most convenient one, if you're putting the text files among your script files:

Dir.chdir(File.dirname(__FILE__))

This will automatically change the current working directory to the same directory as the .rb file that is running the script.

like image 180
Casper Avatar answered Sep 20 '22 15:09

Casper


ENOENT means it's not there.

Just update your code to:

File.open(File.dirname(__FILE__) + '/text.txt').each {|line| puts line}
like image 13
Till Avatar answered Sep 23 '22 15:09

Till


Please use chomp() or chomp() with STDIN

i.e. test1.rb

print 'Enter File name: '

fname = STDIN.gets.chomp()  # or fname = gets.chomp()


fname_read = File.open(fname)

puts fname_read.read()
like image 6
Bhaveshkumar Avatar answered Sep 24 '22 15:09

Bhaveshkumar