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

前端 未结 6 1610
北海茫月
北海茫月 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.

    0 讨论(0)
  • 2020-12-04 18:12

    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.

    0 讨论(0)
  • 2020-12-04 18:16

    Try using

    Dir.glob(".") 
    

    To see what's in the directory (and therefore what directory it's looking at).

    0 讨论(0)
  • 2020-12-04 18:26

    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()
    
    0 讨论(0)
  • 2020-12-04 18:30

    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)
    
    0 讨论(0)
  • 2020-12-04 18:33

    ENOENT means it's not there.

    Just update your code to:

    File.open(File.dirname(__FILE__) + '/text.txt').each {|line| puts line}
    
    0 讨论(0)
提交回复
热议问题