Ruby:没有这样的文件或目录@ rb_sysopen - testfile(错误号::ENOENT)

iqxoj9l9  于 2023-02-15  发布在  Ruby
关注(0)|答案(7)|浏览(194)

我想向文件中写入一些内容。

# 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

当执行这段代码时,我得到了这个错误。我知道这个文件夹不存在,但是如果它不存在,w模式的File.open会创建一个新文件。
为什么这行不通?

vof42yt1

vof42yt11#

File.open(..., 'w')创建一个不存在的文件。没有人承诺它会为它创建一个目录树。
另外,应该使用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
yacmzcpb

yacmzcpb2#

File.open(..., 'w')无法打开文件时,即由于Windows 10下受保护的文件夹访问,您也会收到此错误。

fafcakar

fafcakar3#

在我的情况是因为在方法上面我有:

Dir.chdir(some_folder)

因此它为下一个File.openFile.readlines调用改变当前目录。

jogvjijk

jogvjijk4#

我在尝试用Ruby创建文件时遇到了这个问题。
我正在尝试使用下面的命令创建新文件:

File.new("testfile", "r")

以及

File.open("testfile", "r")

但是我得到了下面的错误:
(irb):1:在"初始化"中:没有这样的文件或目录@rb_sysopen-testfile(错误号::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")
t9eec4r0

t9eec4r05#

我遇到了同样的错误,不得不用URI.open()替换open()

最小可重现示例

这会产生错误

require 'open-uri'
require 'nokogiri'

url = "https://www.example.com"
html_file = open(url)
# Errno::ENOENT: No such file or directory @ rb_sysopen - https://www.example.com

..但在将open()替换为URI.open()后,没有错误:

require 'open-uri'
require 'nokogiri'

# Open the URL
url = "https://www.example.com"
html_file = URI.open(url)
vwoqyblh

vwoqyblh6#

请使用

bundle exec jekyll serve --disable-disk-cache

bundle exec jekyll bui --disable-disk-cache
o2g1uqev

o2g1uqev7#

尝试在rake任务中使用gets?您可能会看到以下错误消息:
错误编号::错误:没有这样的文件或目录@rb_sysopen
你试过搜索错误吗,最后出现在这个页面上?这个答案不是给操作员的,而是给你的。
使用STDIN.gets。问题解决了。这是因为仅仅使用gets就可以解析回$stdin.gets,并且rake正在覆盖全局变量,以便gets尝试打开一个不存在的文件句柄。原因如下:
What's the difference between gets.chomp() vs. STDIN.gets.chomp()?

相关问题