【问题标题】:Getting error while opening file , i have created folder with book_name > chapter_name in code and then creating file打开文件时出错,我在代码中创建了带有 book_name > chapter_name 的文件夹,然后创建了文件
【发布时间】:2016-12-22 09:53:09
【问题描述】:

在子文件夹(章节编号)中,我正在创建文件

#!/usr/bin/env ruby
require 'roo'

Dir.glob("**/*.xlsx") do |file|
  xlsx = Roo::Spreadsheet.open(file)
  bookname = xlsx.column(1)

  cahpter_number_array = xlsx.column(2).uniq

  cahpter_number_array.each do |chapter|
   book_name      = bookname[1] if bookname
   chapter_number = chapter if (cahpter_number_array && (chapter != "Chapter"))

   Dir.mkdir(book_name) unless File.exists?(book_name)
   Dir.mkdir("#{book_name}/#{chapter_number}") unless File.exists?("#{book_name}/#{chapter_number}")

   xlsx.column(3).each do |md|
    output_name = "#{book_name}/#{chapter_number}/#{File.basename(md.partition('-').first, '.*')}.md" if (md != "Verse")
    output = File.open("#{output_name}", 'w')
    output << "hello"
   end
 end
end

错误:

`initialize': 是一个目录@rb_sysopen - 。 (Errno::EISDIR)

以下链接是我的源文件:

source file link

【问题讨论】:

  • 您的示例没有引发该异常
  • 现在你可以检查一下,我已经更改了上面的代码,因为原来的之前是伪代码
  • 现在请投赞成票 :(
  • 请不要乞求支持。
  • 好的!相同的代码向其他人显示错误,而您不知道为什么?

标签: ruby string file


【解决方案1】:

现在,这不是你的代码。您不能在号码上调用分区:

file_name = [1,2,3,4,5,6,7]

file_name.each do |md|
  ... md.partition('-')

所以你会在收到你发布的错误之前得到一个错误。

在任何情况下,错误消息都是说 outputname 设置为等于 "." 并且当 ruby​​ 尝试执行 File.open(".", 'w') 时,ruby 发现 "." 是您系统上的一个目录的名称,并且您不能写目录。这样做你会看到同样的错误:

~/ruby_programs$ mkdir my_dir
~/ruby_programs$ irb
2.3.0 :001 > File.open('my_dir', 'w')
Errno::EISDIR: Is a directory @ rb_sysopen - my_dir
    from (irb):1:in `initialize'
    from (irb):1:in `open'
    from (irb):1
    from /Users/7stud/.rvm/rubies/ruby-2.3.0/bin/irb:11:in `<main>'

【讨论】:

  • 抱歉:我更改了我的代码而不是“md.partition('-')”,请仅使用“md”。上面的代码就像 ["1-3", "4-7"....] 这就是我参与的原因。
  • 我现在更改了所有代码。之前那是伪代码。
  • 我同意你的解决方案,但如果你检查我正在创建文件的行,目录已经创建: output_name = "#{book_name}/#{chapter_number}/#{File.basename(md, '.*')}.md" if (md != "Verse") output = File.open("#{output_name}", 'w') output
  • @umishra,如果在output_name = .... 行之后添加puts "---&gt;#{output_name}&lt;---",你会看到什么?如果您仍然收到相同的错误,那么您应该在错误之前看到输出---&gt;.&lt;---
  • @umishra, above code was like ["1-3", "4-7"....] thats why i was partining--那你为什么打电话给File.basename("1", ".*")?那只是"1"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
相关资源
最近更新 更多