Monday, August 21, 2017

#1 2011-08-21 02:03:52 pm

Registered: 2010-08-22
Posts: 95

How do I save a string to a CSV file using applescript?


I have an applescript that returns a string in the form:

Value13,Value14,Value15,Value16   etc.

I would like to be able to save this string as a CSV file on my desktop but I'm not sure how to do this.

Could someone help me out with this?



Filed under: string, csv



#2 2011-08-23 10:28:09 am

From:: Taulov, Denmark
Registered: 2006-11-02
Posts: 1695

Re: How do I save a string to a CSV file using applescript?

richardhb wrote:

here's a routine that I use.

Richard, I wanted to comment on your code. It's great that you are sharing and I encourage you to do it more. However I need to point out a major flaw in your code. One of the most common mistakes you can make is to tell an application to perform a command that it's not designed to handle. This is very inefficient and often leads to unexpected errors. Since you are sharing your code and thus are teaching others to program, I don't think you want to teach bad habits.

To explain... you have all of the code inside a "tell application Finder" block. Only 2 or 3 lines of your code needs to be performed by the Finder. The rest of it can be done by applescript itself. So please separate the Finder code from the rest of the code. As mentioned it's a good habit to have to avoid errors.

Below is the code I use to write to files. It has error checking and doesn't use the Finder at all. I hope this helps. Here's an example of how to perform the task the user needs, but the "writeTo" handler can be used in all scripts. CSV files are just normal text files (so we write the data as text) with a "csv" file extension.


set filePath to (path to desktop as text) & "theString.csv"
set theString to "Value1,Value2,Value3,Value4

set theResult to writeTo(filePath, theString, text, false)
if not theResult then display dialog "There was an error writing the data!"

on writeTo(targetFile, theData, dataType, apendData)
   -- targetFile is the path to the file you want to write
   -- theData is the data you want in the file.
   -- dataType is the data type of theData and it can be text, list, record etc.
   -- apendData is true to append theData to the end of the current contents of the file or false to overwrite it
       set targetFile to targetFile as text
       set openFile to open for access file targetFile with write permission
       if apendData is false then set eof of openFile to 0
       write theData to openFile starting at eof as dataType
       close access openFile
       return true
   on error
           close access file targetFile
       end try
       return false
   end try
end writeTo

Last edited by regulus6633 (2011-08-23 10:34:59 am)



Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)