ruby Errno::ENOENT(没有那个文件或目录@rb_sysopen

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36350321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:48:32  来源:igfitidea点击:

Errno::ENOENT (No such file or directory @ rb_sysopen

rubyfile

提问by ashwintastic

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 

When this code is executed, I'm getting this error. I know this folder doesn't exist, but File.openwith wmode creates a new file if it doesn't exist.

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

Why is this not working?

为什么这不起作用?

回答by Day Davis Waterbury

Trying to use getsinside a rake task? You may be seeing this error message:

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

Errno::ENOENT: No such file or directory @ rb_sysopen

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

Did you try searching the error, and end up on this page? This answer is not for the OP, but for you.

您是否尝试搜索错误并最终出现在此页面上?这个答案不是给 OP 的,而是给你的。

Use STDIN.gets. Problem solved. That's because just using getsresolves back to $stdin.getsand rake is overriding the global variable so that getstries to open a file handle that doesn't exist. Here's why:

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

What's the difference between gets.chomp() vs. STDIN.gets.chomp()?

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

回答by Aleksei Matiushkin

File.open(..., 'w')creates a file if it does not exist. Nobody promised it will create a directory tree for it.

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

Another thing, one should use File#jointo build directory path, rather than dumb string concatenation.

另一件事,应该使用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