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

ash*_*tic 22 ruby file

我想写一些文件.

# 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 
Run Code Online (Sandbox Code Playgroud)

执行此代码时,我收到此错误.我知道这个文件夹不存在,但File.openw模式创建一个新的文件,如果它不存在.

为什么这不起作用?

Day*_*ury 37

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

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

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

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

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

  • 这也适用于在Vagrantfile中使用`gets'。 (2认同)

Ale*_*kin 25

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
Run Code Online (Sandbox Code Playgroud)