Re: Reading and writing records
Re: Reading and writing records
- Subject: Re: Reading and writing records
- From: has <email@hidden>
- Date: Sat, 25 Aug 2007 15:23:02 +0100
Chris wrote:
Does anyone have a code snippet for writing a list of records one at
a time and reading them back one at a time until eof?
You don't. You slurp the whole list into memory and work on it there.
A more useful question would be: what are you trying to achieve
[...]
For this particular case, I'm wanting to transfer playcounts in iTunes
between different computers. So I don't need random access. The
file is
short lived. And I don't really see the point of slurping tens of
thousands of records into memory when I don't need more than one at
once.
The point is that it's the simplest thing that works. Standard
Additions' read and write commands weren't designed to read/write
arbitrary subsections of serialised lists, only to read and write
them as a single block of data. Really, I wouldn't worry about memory
usage; it's a non-issue with OS X and modern hardware. The only thing
you do need to watch for is AS's abysmal performance when working
with large lists, but there are established kludges for getting
around that.
However, from reading your above description it doesn't sound like
reading/writing AppleScript lists is an essential requirement for
your script after all. So if you really want to read and write single
records, instead of reading/writing an AppleScript list, just open a
file using the 'open for access' command, append the individual
records to it one at a time, then call 'close access' to close it
again when you're done. To read the records back, open the file and
repeatedly read them back again until an end-of-file error is thrown,
then close the file again. (Using the 'open for access'/'close
access' commands makes Standard Additions keep track of the current
read/write position in the file inbetween read/write calls.)
To demonstrate:
-- Script 1: append records to temp file:
set p to POSIX file (get "/tmp/records.tmp")
set f to open for access p with write permission
write {name:"Phineas", age:33} to f as record
write {name:"Franklin", age:31} to f as record
write {name:"Freddy", age:28} to f as record
-- etc...
close access f
--Script 2: read records from temp file one at a time until EOF:
set p to POSIX file (get "/tmp/records.tmp")
set f to open for access p
repeat
try
set rec to read f as record
on error number -39 -- EOF error
exit repeat
end try
-- do stuff with record here
display dialog rec's name & space & rec's age
end repeat
close access f
HTH
has
--
http://appscript.sourceforge.net
http://rb-appscript.rubyforge.org
_______________________________________________
Do not post admin requests to the list. They will be ignored.
AppleScript-Users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
Archives: http://lists.apple.com/archives/applescript-users
This email sent to email@hidden