简体   繁体   中英

ruby: Can't create new file

I have a command line program that asks the user a set of questions and stores them in a file. The only problem is, I need it to create a new file and it won't.

Here is what I have tried: File.open("path/to/file", "w")
and File.open("path/to/file", "w+")

Both times I get this error
in 'initialize': No such file or directory @ rb_sysopen - path/to/file (Errno::ENOENT)

Here is my current code:
File.open("path/to/file", "w") { |f| f.write(array.join("\\n")) }

When someone writes path/to/file in a blog post or documentation, they don't intend for you to literally write path/to/file in your code. The point is that you need to edit that string to actually have the real path to your file, either as a relative path or an absolute path.

You said you are getting this error from the Ruby interpreter:

No such file or directory @ rb_sysopen - path/to/file (Errno::ENOENT)

This means that in the current working directory, there is no directory named "path", or if there is a directory named "path", then it doesn't have a child directory named "to".

You could solve the immediate problem by running mkdir -p path/to , but that would be weird. It is better to just write an appropriate path in your code, pointing to a directory that already exists. Try changing the path to simply be output.txt (without any slashes) and see how that works.

Ensure you are using an absolute path, and if so, make sure the directory you want to store the file in is missing. Try creating it first:

require 'fileutils'
FileUtils.mkdir_p '/path/to'
File.open('/path/to/file', 'w') { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM