Errno :: ENOENT(没有这样的文件或目录@ rb_sysopen

我想写一些文件。

# where userid is any intger [sic] path = Rails.root + "public/system/users/#{user.id}/style/img.jpg" File.open(path, 'wb') do |file| file.puts f.read end 

执行此代码时,我收到此错误。 我知道这个文件夹不存在,但是如果不存在,带有w模式的File.open会创建一个新文件。

为什么这不起作用?

如果文件不存在File.open(..., 'w')会创建一个文件。 没有人承诺会为它创建一个目录树。

另一件事,一个应该使用File#join来构建目录路径,而不是哑字符串连接。

 path = File.join Rails.root, 'public', 'system', 'users', user.id.to_s, 'style' FileUtils.mkdir_p(path) unless File.exist?(path) File.open(File.join(path, 'img.jpg'), 'wb') do |file| file.puts f.read end 

试图使用gets佣金任务? 您可能会看到此错误消息:

Errno :: ENOENT:没有这样的文件或目录@ rb_sysopen

您是否尝试搜索错误,并最终在此页面上? 这个答案不适用于OP,而是适合您。

使用STDIN.gets 。 问题解决了。 那是因为只是使用gets解析回$stdin.gets并且rake覆盖全局变量,以便尝试打开不存在的文件句柄。 原因如下:

gets.chomp()与STDIN.gets.chomp()之间有什么区别?