Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error
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.
ENOENT
means it's not there.
Just update your code to:
File.open(File.dirname(__FILE__) + '/text.txt').each {|line| puts line}
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()
Try using
Dir.glob(".")
To see what's in the directory (and therefore what directory it's looking at).