Ruby: No such file or directory @ rb_sysopen - testfile (Errno::ENOENT)
Solution 1
File.open(..., 'w')
creates a file if it does not exist. Nobody promised it will create a directory tree for it.
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
Solution 2
Trying to use gets
inside a rake task? You may be seeing this error message:
Errno::ENOENT: No such file or directory @ rb_sysopen
Did you try searching the error, and end up on this page? This answer is not for the OP, but for you.
Use STDIN.gets
. Problem solved. That's because just using gets
resolves back to $stdin.gets
and rake is overriding the global variable so that gets
tries to open a file handle that doesn't exist. Here's why:
What's the difference between gets.chomp() vs. STDIN.gets.chomp()?
Related videos on Youtube
ashwintastic
It's all about the Geeks who changed the world....
Updated on February 20, 2022Comments
-
ashwintastic over 2 years
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.open
withw
mode creates a new file if it doesn't exist.Why is this not working?
-
user1934428 about 8 yearsJust being curious: Why is is File.join advisable here? It joins the path components always with the platform specific separator (for instance,
` on Windows). While there **are** cases, where this is what we want to achive, we usually try to stick with
/` on all platforms, because this gives less headache with respect of portability. In the case of the code posted here, I don't see why platform-specific file separators could be an advantage. -
Aleksei Matiushkin about 8 years@user1934428 “we usually try to stick with / on all platforms, because this gives less headache with respect of portability”—besides this is nonsense, using
File.join
helps to avoid silly mistakes like the one in the OP:Rails.root
does not end with a slash and using+
gives/railsrootpublic/
(note the slash miss above.) -
ashwintastic about 8 years@mudasobwa: In my rails console Rails.root + "bla/bla" GIves correct path :)
-
ashwintastic about 8 years@mudasobwa : it worked but I have to make some changes like Dir.mkdir only create directory not a directory tree, I used FileUtils.mkdir_p : thnk for the help
-
bschlueter almost 7 yearsThis also applies to use of
gets
inside of a Vagrantfile.