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?
This question is related to
ruby
Next to being in the wrong directory I just tripped about another variant:
I had a File.open(my_file).each {|line| puts line}
exploding but there was something by that name in the directory I was working in (ls in the command line showed the name). I checked with a File.exists?(my_file)
which strangely returned false
. Explanation: my_file
was a symlink which target didn't exist anymore! Since File.exists?
will follow a symlink it will say false
though the link is still there.
ENOENT
means it's not there.
Just update your code to:
File.open(File.dirname(__FILE__) + '/text.txt').each {|line| puts line}
Ditto Casper's answer:
puts Dir.pwd
As soon as you know current working directory, specify the file path relatively to that directory.
For example, if your working directory is project root, you can open a file under it directly like this
json_file = File.read(myfile.json)
Try using
Dir.glob(".")
To see what's in the directory (and therefore what directory it's looking at).
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()
Source: Stackoverflow.com