我在尝试在 Ruby 中创建文件时遇到了这个问题。
我试图使用下面的命令来创建一个新文件:
File.new("testfile", "r")
和
File.open("testfile", "r")
但后来我收到以下错误:
(irb):1:in `initialize': 没有这样的文件或目录@rb_sysopen - testfile (Errno::ENOENT)
这是我修复它的方法:
问题是我没有为文件指定正确的模式。创建新文件的格式为:
File.new(filename, mode)
或
File.open(filename, mode)
各种模式分别是:
"r" Read-only, starts at beginning of file (default mode).
"r+" Read-write, starts at beginning of file.
"w" Write-only, truncates existing file
to zero length or creates a new file for writing.
"w+" Read-write, truncates existing file to zero length
or creates a new file for reading and writing.
"a" Write-only, each write call appends data at end of file.
Creates a new file for writing if file does not exist.
"a+" Read-write, each write call appends data at end of file.
Creates a new file for reading and writing if file does
not exist.
但是,我的命令 File.new("testfile", "r") 正在使用 "r" Read-only 模式,该模式试图从名为 testfile 的现有文件中读取,而不是创建新文件。我所要做的就是修改命令以使用"w" Write-only 模式:
File.new("testfile", "w")
或
File.open("testfile", "w")
参考:File in Ruby