"Is a directory" error when it should not be a directory

Asked 2 years ago, Updated 2 years ago, 41 views

I have a program that reads the files in the directory and outputs the contents of the files.

 in `read': Isa directory

The error appears.

I think you're probably saying, "That's a directory," but since you've verified the file in the previous if statement, it should be the path of the text file, not the directory.

Why does this error occur?

require "find.rb"

Find::find("/Users/tamada/Desktop/Review Dev/Recipe Data Perspective Material/Test Data/recipe/") do | path | 
    ifFileTest.file?(path)||FileTest.readable?(path)then
        # p "File: " + path
        file=open(path)
        text=file.read
        ptext
        file.close
    end 
end

ruby

2022-09-30 17:49

1 Answers

(The "Resolved" answer has been deleted.) If it has been resolved, you should state what the problem was.
Perhaps the FileTest.readable?(path) statement was unnecessary.

    The
  • Find.find method enumerates files below the directory for arguments.Include the directory itself.
  • The
  • FileTest.#readable? method returns whether or not you have read permission, so the directory also returns true.

I'm sorry, but I refactored it.

require "find"

Find.find("/Users/tamada/Desktop/Review Dev/Recipe Data Perspective Material/Test Data/recipe/") do | path | 
  ifFileTest.file?(path)
    open(path)do|f|
      puts f.read
    end
  end
end

List the points.

    The
  • Kernel#require method argument is library name only and is abbreviated with an extension (by contrast Kernel#load is required).
  • The class method uses :: such as Find::find.Find.find is common (but it was an old notation in the recent book "Effective Ruby" ^^;)
  • Ruby style is to not use then in the
  • if statement.
  • For IO-handling methods such as the
  • Kernel#open method, Ruby is the way to use blocks instead of using them because you tend to forget to close them.
  • p is a debugging-only method.Use puts for output (although it may still be in the middle of debugging).
  • I think it is better to use file.read/f.read as the argument for p/puts instead of using the
  • variabletext.I think it's harder to make mistakes if there are fewer variables.


2022-09-30 17:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.