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

前端 未结 6 1649
北海茫月
北海茫月 2020-12-04 18:03

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 l         


        
6条回答
  •  死守一世寂寞
    2020-12-04 18:06

    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.

提交回复
热议问题