Errno :: ENOENT(无此类文件或目录@ rb_sysopen [英] Errno::ENOENT (No such file or directory @ rb_sysopen
本文介绍了Errno :: ENOENT(无此类文件或目录@ rb_sysopen的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在文件中写一些东西.
I want to write something to a 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
执行此代码时,出现此错误.我知道此文件夹不存在,但是如果File.open
模式为w
模式,则File.open
会创建一个新文件(如果不存在).
When this code is executed, I'm getting this error. I know this folder doesn't exist, but File.open
with w
mode creates a new file if it doesn't exist.
为什么这不起作用?
推荐答案
File.open(..., 'w')
如果文件不存在,则会创建一个文件.没有人保证会为其创建目录树.
File.open(..., 'w')
creates a file if it does not exist. Nobody promised it will create a directory tree for it.
另一件事,应该使用 File#join
构建目录路径,而不是哑字符串连接.
Another thing, one should use File#join
to build directory path, rather than dumb string concatenation.
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
这篇关于Errno :: ENOENT(无此类文件或目录@ rb_sysopen的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文