Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!us.feeder.erje.net!news2.arglkargh.de!news.swapon.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.ruby Subject: Re: *Could use some help here* Ruby script that downloads .png files that are ordered in sequence and saves them locally. Date: Fri, 08 Feb 2013 08:23:47 +0100 Lines: 71 Message-ID: References: <77215246-6e96-42c9-a8ca-187050e777ee@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net u+1UTLHsEZKR33fFyBkg6gJNXamSLF1V/OOOT+TNR3mUrCyLlwVHp89/jCHfyL5gI= Cancel-Lock: sha1:+NRZXZgd9O0SVP4fsAWOpppFR4U= User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:17.0) Gecko/20130107 Thunderbird/17.0.2 In-Reply-To: <77215246-6e96-42c9-a8ca-187050e777ee@googlegroups.com> Xref: csiph.com comp.lang.ruby:6737 On 07.02.2013 23:36, patrick.anthony124@gmail.com wrote: > Hey everyone. This is the first time I've written something in Ruby to do something for myself, everything else has been some how part of an assignment or a tutorial or a walk-through. I want this script to download a series of .png files and save them locally in the same order. I have posted it below but it just doesn't seem to work. Any help or suggestions would be greatly appreciated. > > require "net/http" > remote_base_url = "https://path.to/the/folder" > > start_page = 001 > end_page = 281 The reason is probably that you use integers here. Note: irb(main):001:0> x = 001 => 1 irb(main):002:0> puts x 1 => nil Leading zeros are removed. If you use that (and I would recommend using integers here) you must ensure the zeros are added when creating URLs: > # Images are named p001.png to p281.png. > (start_page..end_page).each do |it| > rpage = open(remote_base_url + "/" + "p" + it.to_s) # example: rpage = open(sprintf("%s/p%0d", remote_base_url, it)) > local_fname = "copy-of-" + it.to_s + ".png" # other approach local_fname = "copy-of-%03d.png" % it > local_file = open(local_fname, "w") > local_file.write(rpage.read) > local_file.close > # Optional output line: > puts "Wrote file " + local_fname > sleep 1 Why the sleep? > end > > # Write to the compiled file now: > compiled_file = open(start_page.to_s + "-" + end_page.to_s + ".png", "w") > (start_page..end_page).each do |it| > local_fname = "copy-of-" + it.to_s + ".png" > local_file = open(local_fname, "r") > > compiled_file.write(local_file.read) > local_file.close > end > > compiled_file.close And a general remark: you should use the block form of #open instead of the explicit #close call. This is much more robust because it ensures files are always closed. See my blog post for more details http://blog.rubybestpractices.com/posts/rklemme/002_Writing_Block_Methods.html Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/