Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Write output to multiple files

Reply
Thread Tools

Write output to multiple files

 
 
Milo Thurston
Guest
Posts: n/a
 
      04-23-2009
I have encountered something I thought would be trivial but I can't
quite get it to work properly. I have a load of data that is stored in
various locations and need to create several files, one for each
location, each containing the data in that location. Getting an array of
objects containing the file name and location is easy, so I was thinking
along the lines of this pseudocode:

data.each do |d|
output_filename = "#{d.location}.txt"
if !File.exists?(output_filename)
# create it and write d.file_name to it
else
# simply write d.file_name to it
end
end
# close all open files

The locations of the data are numerical ids so I could expect filenames
like 1.txt, 2.txt and so on, and I have also sorted them before
processing so that they could be opened and filled sequentially. But, it
is not clear to me how to properly manage the file handles so any
suggestions would be welcome.
--
Posted via http://www.ruby-forum.com/.

 
Reply With Quote
 
 
 
 
Milo Thurston
Guest
Posts: n/a
 
      04-23-2009
Robert Klemme wrote:

> If I understood you properly:
>
> # untested
> last_name = nil
> io = nil
> begin
> data.sort_by {|d| d.location}.each do |d|
> output_filename = "#{d.location}.txt"
>
> unless output_filename == last_name
> io.close rescue nil
> io = File.open(output_filename, "a")
> end
>
> io.puts d.file_name
> ensure
> io.close rescue nil
> end



Yes, that looks like just the job, thanks. I was trying something
similar but without the begin/ensure/end block and that is presumably
why I was having difficulty.
--
Posted via http://www.ruby-forum.com/.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: It seems that ZipFile().write() can only write files,how can empty directories be put into it? could ildg Python 0 07-02-2005 08:31 AM
Re: It seems that ZipFile().write() can only write files,how can empty directories be put into it? Jeff Epler Python 0 07-01-2005 02:06 PM
It seems that ZipFile().write() can only write files,how can empty directories be put into it? could ildg Python 0 07-01-2005 01:50 AM
Re: output from multiple files Alan Connor Perl 0 04-28-2005 09:56 AM
Text files read multiple files into single file, and then recreate the multiple files googlinggoogler@hotmail.com Python 4 02-13-2005 05:44 PM



Advertisments