我必须通过多个请求从网上下载文件。每个请求的下载文件必须放在与请求编号同名的文件夹中。
例如:
我的脚本现在正在运行以下载请求号为87665的文件。因此,所有下载的文件都将放在目标文件夹Current Download\Attachment87665
中。那我该怎么做呢?
目标文件夹: Current Download
已修复。只需动态创建Attachmentxxxxxx
,其中xxxxxx
任意请求号。
这是代码的Python版本: 但我希望它在Ruby中,仅供您参考以了解我在寻找什么
request_number = 82673
# base dir
_dir = "D:\Current Download"
# create dynamic name, like "D:\Current Download\Attachment82673"
_dir = os.path.join(_dir, 'Attachment%s' % request_number)
# create 'dynamic' dir, if it does not exist
if not os.path.exists(_dir):
os.makedirs(_dir)
答案 0 :(得分:2)
使用Dir.mkdir("#{Rails.root}/#{whatever}/#{example.join('bla')}")
。
http://www.ruby-doc.org/core-1.9.3/Dir.html#method-c-mkdir
答案 1 :(得分:2)
可以同时进行多次下载吗?如果是这样,你需要能够随机创建数字的东西而不会发生碰撞。
看一下Ruby的Tempfile模块,它是为了做你正在谈论的事情,特别是open
方法。
用于管理临时文件的实用程序类。创建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
另请阅读有关“明确关闭”和“创建后取消链接”的文档。
无论您做什么,给定文件夹中存在的文件越多,系统或代码生成唯一文件名所需的时间就越长。
您也可以使用数据库来跟踪序列号。
而且,“Generate unique filenames”也谈到了这个问题,有许多解决方案。最好的可能是在* nix系统上使用uuidgen
。
uuidgen命令生成通用唯一标识符(UUID),128位值保证在空间和时间上都是唯一的。