簡體   English   中英

ruby 臨時目錄中的臨時文件

[英]ruby Temporary files inside temporary directory

我想在臨時目錄中創建臨時文件。 下面是我的代碼。

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

它給了我這個例外: 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

您應該使用Tempfile類。

require 'tempfile'

file = Tempfile.new('foo')
file.path      # => A unique filename in the OS's temp directory,
               #    e.g.: "/tmp/foo.24722.0"
               #    This filename contains 'foo' in its basename.
file.write("hello world")
file.rewind
file.read      # => "hello world"
file.close
file.unlink    # deletes the temp file

要創建臨時文件夾,您可以使用Dir.mktmpdir

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM