Welcome to the MacNN Forums.

If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

You are here: MacNN Forums > Software - Troubleshooting and Discussion > Developer Center > Frustrated AppleScript Beginner!

Frustrated AppleScript Beginner!
Thread Tools
Just
Fresh-Faced Recruit
Join Date: May 2001
Status: Offline
Reply With Quote
May 22, 2001, 09:19 AM
 
Hello,

I don't know what anybody means by applescipt is an easy language to learn because I now have two books on applescript (AppleScript for Dummies and Visual Quickstart Applescript). I'm still unable to perform on my own what seems to be simple file handling functions that I did manually. Is this the type of thing that a beginner should be able to do?
Three days ago I posted a note in this forum about trying to write a script that opens a file based on the file extension ".txt" rather then the actual name of the file which is a series of numbers that precedes ".txt".A member of this forum graciously offered a script that solved my problem.
I then tried to study his/her script to learn the thought process for myself (two books later). I understand what is taking place in his script but I don't yet understand why the choices where made when I see other combinations that would seem to make sence to me but applescipt doesn't aggree. Example:tell application "Finder"
open file filetoOpen
tell application "Finder"
activate
tell application "Finder"
copy file filetoOpen
tell application "Finder"
close file filetoOpen
end tell
end tell
end tell
end tell
This bit of script is my addition to the script that solved the initial problem but once the desired file is open I would like to continue working with it in a script. Basically once the file is open I want to copy the file to the clipboard, close the file, send the file to another folder which is labeled by the month so that all files are placed in a folder of the appropriate month that it was downloaded, and take the copy which is on the clipboard and paste it into a text field of filemakerpro 5 database. Problem is I can't even get out of the dugout on my own!
Now this is a copy of the functioning script that was created for me.


------------------------------------------------------------------------
property file_Ext : ".txt"
property theFolder : alias "Macintosh HD:MyDocuments:" (*change to the path to your folder of choice*)
set text_List to {} -- always start with an empty list of files
set filesList to list folder theFolder without invisibles
repeat with anItem in filesList -- find all files ending in file_Ext in theFolder
set theFile to (theFolder as string) & contents of anItem
set fileInfo to info for alias theFile
if the name of the fileInfo contains file_Ext then
copy name of fileInfo to the end of text_List
end if
end repeat
if (count of text_List) > 1 then
-- if multiple files ending in file_Ext found, choose the file(s) to open
set slctd_Files to (choose from list (text_List) with prompt "Please choose a text file to open" with multiple selections allowed) as list
repeat with aFile in slctd_Files -- opens all files selected in the dialog
set filetoOpen to (theFolder & aFile) as string
tell application "Finder"
open file filetoOpen
end tell
end repeat
else -- only one file ending in file_Ext found in theFolder
set filetoOpen to (theFolder & (text_List as string)) as string
tell application "Finder"
open file filetoOpen
end tell
end if
Would someone please tell me why my addition to the script isn't working???
I was trying to add my bit of script towards the end of the one above starting right after tell application "finder"
Open file filetoOpen.

Thanks, Steph
     
acur128
Junior Member
Join Date: May 2001
Status: Offline
Reply With Quote
May 22, 2001, 10:46 PM
 
Steph,
Sorry for the delay... just saw your last post - i check these boards somewhat regularly (at least lately), but this particular forum is so slow sometimes that i miss stuff.
As for some good sites for learning applescript, i like Macscripter.net for news, scripting additions (osax) that supplement the built-in functionality of applescript, and especially for the Bulletin Board System - which has a wealth of information on troubleshooting applescript... essentially like these forums but dedicated to applescript questions. Most of the time, you'll get a quick response & some great examples for getting started and troubleshooting. And also check out the Applescript Links section for dozens of more links. There's Bill Cheeseman's site, AppleScript Sourcebook, another great site for examples, news, and the tips section is very good. And there's also Bill Briggs' Applescript Primers which covers the ins & outs of various scripting routines. And lots more - Sherlock searches for applescript + your scripting term of interest often digs up postings from the classic Macscrpt Digest forums, which are usually very helpful & still applicable.
So, there's usually lots of great places for assistance, which i kind of wish i had taken advantage of, or known about, years ago.

About that script... it's no cakewalk in terms of scripting - there's a lot of elements that come into play; the trick is getting all of them to work well together. As you've probably noticed, there's usually any number of ways to set up a script to get it to do exactly what you want it to do - and it often just comes down to habits for performing certain tasks with certain routines. Sometimes you'll need indirect methods for getting a script to do what you need it to do, as the applescript language is not comprehensive (so the need for scripting additions), and a script will often force you to give it directions in exactly the format it wants to hear them.

Also, certain tasks are best delegated to, and may only be understood by, certain applications, each of which has it's own dictionary. You'll notice that scriptable apps and scripting additions are your friends... to get started with them, open their dictionaries (from Script Editor, File -> Open Dictionary..., then choose the application or scripting addition you're interested in). Sometimes the syntax is obvious, and sometimes it's obscure, poorly documented, and impossible to implement - maybe stay away from those ones. You'll also notice that without scripting additions only the Finder knows how to move/duplicate/rename/set information (not all) for files. It's often best to delegate responsibility for a task to the application that knows how to do that task best, then . And if the script can perform the task itself without telling another application, by all means let it. This is especially true of the Finder, which is notoriously slow in scripts, and appears to have bigger fish to fry... if you don't keep it continually busy in the script, it will force the script to stop.

One other thing, most of the time, you only need to address the application once to get it's attention (and usually in later versions of applescript, the application will automatically "activate" if you address it), and delegate responsibility as needed. If you're telling the same app to do do something else, you can omit the extra "tell" block. So you could say:

tell application "Finder"
select file filetoOpen
duplicate file filetoOpen to desktop
open file filetoOpen
end tell

In your additions to the script, The Finder can open the file, but of course then the frontmost app is SimpleText... so to get the Finder's attention again, you'd have to say something like:
tell application "Finder" to (do something)
Which you did, but unfortunately, the Finder only knows 2 meanings for "copy":
duplicate the file itself to some location, or
copy some data to a record of some sort
And so the Finder is left wondering where to copy the data, and what data to copy. To copy text from an open document would usually require that functionality in the application's dictionary (& SimpleText doesn't have that built-in dictionary) or a scripting addition. For example, there's a scripting addition that simulates keyboard activity, which would allow you to simulate pressing command-A (select all) and command-c (copy) which would put the text on the clipboard.

Another way to extract data (text) from a file is to use the "open for access", "read", and "write" commands from the "Standard Additions" scripting addition that is automatically installed with applescript. These commands allow you to open the data fork of the file, read it's contents & make them into an item (variable), and write them somewhere. This is what I've used in the example below... I omitted the part about opening the file, since you don't need it open in a text editor to get the text data from it, and neither the Finder nor SimpleText knows how to close the file... best way to do that would be to say:
tell application "SimpleText" to quit

Anyway, here's the script. Let me say that although I have FileMaker Pro 5, I have NEVER used it, so the part about FileMaker Pro is just an example - it will get the beginning of the text into a cell, but will stop after the first carriage return in the text. There are some secrets to entering data in FileMaker from a script that would take some time to work out. Specifically, you may need to tell it to import the text in blocks, using a delimiter of some sort (like returns). If I come up with anything, I'll let you know, as I'm interested in setting up some databases. There's also a handy built-in scripting functionality (as well as several examples somewhere in its folder) in FileMaker for running scripts from within the app. To set the name of the storage folder, the current date function is handy. Whomever told you applescript was an easy language to learn may have been thinking of something else.

Here's that script... again, change the names where indicated, & the FileMaker stuff needs some work to get it going. For some quick help with that, I've noticed there are a few seasoned FileMaker scripters over at the Macscripter.net bulletin boards (see link above).
Hope it helps...

Oh yeah; the separate handler (on something... in this case, "on process_File(filetoOpen)" is to separate out the text reading & FileMaker import stuff, so the script doesn't "remember" that info the next time it's run - variables tend to carry over between runs of the script unless you tell the script to deal with them only when requested (by the handler)

Good luck, & post back if you have any other questions.
acur

Code:
property file_Ext : ".txt" property theFolder : alias "Macintosh HD :Documents:" (*change to the path to your folder of choice*) set text_List to {} -- always start with an empty list of files set filesList to list folder theFolder without invisibles repeat with anItem in filesList -- find all files ending in file_Ext in theFolder set theFile to (theFolder as string) & contents of anItem set fileInfo to info for alias theFile if the name of the fileInfo contains file_Ext then copy name of fileInfo to the end of text_List end if end repeat if (count of text_List) > 1 then -- if multiple files ending in file_Ext found, choose the file(s) to open set slctd_Files to (choose from list (text_List) with prompt "Please choose a text file to open" with multiple selections allowed) as list repeat with aFile in slctd_Files -- opens all files selected in the dialog set filetoOpen to (theFolder & aFile) as string process_File(alias filetoOpen) end repeat else -- none found, or only one file ending in file_Ext found in theFolder try set filetoOpen to (theFolder & (text_List as string)) as string process_File(alias filetoOpen) on error -- no files found ending in file_Ext in theFolder display dialog ("No files ending in '.txt' were found in the folder '" & theFolder & "'") buttons {"OK"} default button "OK" with icon 1 end try end if on process_File(filetoOpen) -- handler for getting text data from file & importing into FileMaker. set fldr_Name to ("TextFiles " & (month of (current date) & (year of (current date)))) as string (*change "TextFiles" to your name of choice*) set txtFile_Folder to (("Macintosh HD :Documents:TextFiles:" & fldr_Name) as string) (*change to the path to the folder where you want to store all the dated folders*) set file_Data to open for access filetoOpen set textInfo to read file_Data as text close access file_Data tell application "Finder" if not (exists of alias txtFile_Folder) then -- if the dated folder for the current month isn't there, make it! make folder at desktop with properties {name:txtFile_Folder} end if move file filetoOpen to alias txtFile_Folder end tell tell application "FileMaker Pro" tell database "TextFileDB.fp5" (*change to the name of your FileMaker database*) set new_Rec to create new record with data textInfo end tell end tell end process_File
[This message has been edited by acur128 (edited 05-22-2001).]
     
Just  (op)
Fresh-Faced Recruit
Join Date: May 2001
Status: Offline
Reply With Quote
May 23, 2001, 12:32 AM
 
Hi,

Thank you for the detailed explanation. I tried to run the script but I had two errors. The first one I was able to adjust. That was where in the script you wrote if (count of text_list)> 1. I changed to 1 to O because I was getting the error that there wasn't any ".txt" file although there was one. I only ever have one of these type files in that folder at a time since I moved the file immediately after downloading into another file which was titled by month and year. Though I'm not sure why it worked in your original script but not on the revised script.
The second error was that a folder with the month and date already exist and for me to choose another name. Why is that? I can see in your script that you a lotted for the existence of such a folder and if it didn't exist to create it. Anyway that is where the script crashes. By the way can eliminate the dialogue box for me to select which ".txt" file since there is only one anyway. The actions I take with the file never vary since there is an exact sequence of activities for this file type.

Thank you, Steph
     
acur128
Junior Member
Join Date: May 2001
Status: Offline
Reply With Quote
May 23, 2001, 05:40 AM
 
maybe see if this one works out any better for you... takes a different approach to the issues you mentioned, and a few other tasks were cleaned up.
btw, make sure you change all the folder & file names to ones that are actually residing on your computer... if the script can't make sense out of them (can't find the folders you're pointing to), it would claim the item you're trying to make already exists (it gets a little confused).
-acur
Code:
property file_Ext : ".txt" property theFolder : alias "Macintosh HD :Documents:" (*change to the path to your folder of choice*) set text_List to {} -- always start with an empty list of files set AppleScript's text item delimiters to {} -- no delimiters just yet, thank you set filesList to list folder theFolder without invisibles repeat with anItem in filesList -- find all files ending in file_Ext in theFolder set theFile to (theFolder as string) & contents of anItem set fileInfo to info for alias theFile if the name of the fileInfo contains file_Ext then copy name of fileInfo to the end of text_List end if end repeat if (count of text_List) = 0 then -- no .txt files found display dialog ("No files ending in '.txt' were found in the folder '" & theFolder & "'") buttons {"OK"} default button "OK" with icon 1 else -- success (only one .txt file allowed though) set filetoOpen to (theFolder & (text_List) as string) as string process_File(alias filetoOpen) end if on process_File(filetoOpen) -- handler for getting text data from file & importing into FileMaker. set datedf_Loc to "Macintosh HD :Documents:TextFiles:" (*change to the path to the folder where you want to store all the dated folders*) set fldr_Name to ("TextFiles " & (month of (current date) & (year of (current date)))) as string (*change "TextFiles" to your name of choice*) set txtFile_Folder to ((datedf_Loc & fldr_Name) as string) set AppleScript's text item delimiters to {" "} -- now, 2 spaces in place of carriage returns in the text set file_Data to open for access filetoOpen without write permission set textInfo to read file_Data using delimiter return as text -- yeah, get rid of those carriage returns; FileMaker doesn't like 'em set FP_Data to textInfo as string close access file_Data set AppleScript's text item delimiters to {} -- & back to normal tell application "Finder" try -- try to "get" that dated folder alias txtFile_Folder on error -- can't get it; must not be there... make it then make folder at alias datedf_Loc with properties {name:fldr_Name} end try move file filetoOpen to alias txtFile_Folder end tell tell application "FileMaker Pro" open "TextFileDB.fp5" (*change to the name of your FileMaker database*) tell database "TextFileDB.fp5" (*& here also*) set new_Rec to create new record with data FP_Data end tell end tell end process_File
darn smilies...

[This message has been edited by acur128 (edited 05-24-2001).]
     
Just  (op)
Fresh-Faced Recruit
Join Date: May 2001
Status: Offline
Reply With Quote
May 23, 2001, 03:27 PM
 
Hi Acur,

I'm still having the same problem because the file for May already exist. I'm getting an error that the file already exist to pick another name. I think the problem might be somewhere in this area,

process_File(alias filetoOpen)
end if
on process_File(filetoOpen) -- handler for getting text data from file & importing into FileMaker.
set fldr_Name to ("TextFiles " & (month of (current date) & (year of (current date)))) as string (*change "TextFiles" to your name of choice*)
set txtFile_Folder to (("Macintosh HD ocuments:TextFiles:" & fldr_Name) as string) (*change to the path to the folder where you want to store all the dated folders*)
set AppleScript's text item delimiters to {" "} -- now, 2 spaces in place of carriage returns in the text


Right after the line on process_file(FiletOpen), the script goes right into set fld_Name. Well it can't set a folder name that already exist can it? Wouldn't that be confusing? I would think that the script needs to know that the file might already exist and if it doesn't exist for the current month then set fld_Name. I'm guessing this might have something to do with it.
By the way about the simple text issues of no delimiters, structure, and extra carriage returns, I created a parsing engine with filemaker pro that cleans it up then it gets inserted into a real database. Your right, filemaker doesn't like simpltext type documents for importing into a database. Now maybe your idea is better. I could eliminate the parsing engine database altogether but then this particular script has potential for being a nightmare due to my lack of experiance. My money is on you so I will give it a shot if you think it's worth it.
In the mean time I fear that if I use applesrcipt to clean up the carriage returns then it will throw my parsing engine off. The parsing engine as of now functions with actual text as is.
By the way I e-mailed you at the e-mail address you have included in your profile at this site. I was wondering did you get the e-mail?
The e-mail address I gave for this site I check only every two to three days. The return e-mail address is the one I check at least two times a day. I use that for my business. Tag your it!!!
Thank you, Steph
     
Camelot
Mac Elite
Join Date: May 1999
Location: San Jose, CA
Status: Offline
Reply With Quote
May 24, 2001, 03:21 PM
 
Going back to the original poster's question, the first mistake you're making is telling the Finder to open the document.

Doing this, you have little or no control over which application opens the document, and therefore what you can do with it once it's open.

Since you're working with .txt files, they'll presumably open in SimpleText, which, being an Apple program, has absolutely ZERO AppleScript support (WTG Apple!).

You are much better off opening the document directly using the application of choice. e.g.:

tell application "BBEdit"
open {file fileToOpen}
end tell

Now you know you have the document you want, and it's somewhere you can do something with it. Since BBEdit is beautifully scriptable, you can easily extract the text from the document.

Within the 'tell/end tell' statements, add:

set theText to (contents of window 1) as text

Now you have the contents of that document in a variable called 'theText'

Now all you need to do is create a new record in Filemaker and put 'theText' into the relevant field.

As has been mentioned before, you may be better off opening the file directly using the 'open for access' or 'read file' osax. This will save you the trouble of launching a text editor to get the text, but is a little more advanced.

As for the issue regarding the complexity of AppleScript as a language, it's all dependant on the applications you use. In this case you were getting caught by trying to use <insert favorite expletive here> SimpleText rather than a program that understands AppleScript. In my experience, avoid using any Apple-authored application when AppleScripting. They seem unable to eat their own dog food, even though they want every other developer to do so.

AppleScripting is more about knowing the programs you use than knowing any kind of programming lanaguage.
Gods don't kill people - people with Gods kill people.
     
   
 
Forum Links
Forum 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
Top
Privacy Policy
All times are GMT -4. The time now is 06:02 AM.
All contents of these forums © 1995-2017 MacNN. All rights reserved.
Branding + Design: www.gesamtbild.com
vBulletin v.3.8.8 © 2000-2017, Jelsoft Enterprises Ltd.,