gpt4 book ai didi

ruby-on-rails - ruby 临时目录中的临时文件

转载 作者:行者123 更新时间:2023-12-04 05:52:36 29 4
gpt4 key购买 nike

我想在临时目录中创建临时文件。下面是我的代码。

           require 'tmpdir'
require 'tempfile'
Dir.mktmpdir do |dir|
Dir.chdir(dir)
TemFile.new("f")
sleep 20
end

它给了我这个异常(exception): Errno::EACCES: Permission denied - C:/Users/SANJAY~1/AppData/Local/Temp/d20130724-5600-ka2ame ,因为 ruby​​ 正在尝试删除一个非空的临时目录。

请帮我在临时目录中创建一个临时文件。

最佳答案

嗨,我创建了前缀为“foo”的临时目录和前缀为cats的临时文件

dir = Dir.mktmpdir('foo')
begin
puts('Directory path:'+ dir) #Here im printing the path of the temporary directory

# Creating the tempfile and giving as parameters the prefix 'cats' and
# the second parameter is the tempdirectory
tempfile = Tempfile.new('cats', [tmpdir = dir])

puts('File path:'+ tempfile.path) #Here im printing the path of the tempfile
tempfile.write("hello world")
tempfile.rewind
tempfile.read # => "hello world"
tempfile.close
tempfile.unlink
ensure
# remove the directory.
FileUtils.remove_entry dir
end

由于我们在控制台上打印路径,我们可以获得以下信息
Directory path: /tmp/foo20181116-9699-1o7jc6x
File path: /tmp/foo20181116-9699-1o7jc6x/cats20181116-9699-7ofv1c

关于ruby-on-rails - ruby 临时目录中的临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17833186/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com