AppleScript - array read from disk is empty - applescript

I have a script that starts like this:
tell application "Finder"
set theFolder to (choose folder)
set theFile to POSIX path of ((theFolder as string) & "words.txt")
set fileHandle to open for access theFile
set nameArray to paragraphs of (read fileHandle for (get eof fileHandle) as «class utf8»)
close access fileHandle
end tell
File words.txt is there and contains one word per line.
theFile is a valid path to words.txt, something like /Users/myself/Desktop/folder/words.txt.
nameArray comes empty.
Why?
If instead of letting the user choose the folder, I hardcode the path, like
set theFile to "/Users/myself/Desktop/folder/words.txt"
everything works fine.

First of all, you do not need Finder as the necessary commands are just basic AppleScript commands and or are all a part of Standard Additions.
The following three lines, by themselves, will do what you are trying to do:
set theFolder to (choose folder)
set theFile to POSIX path of ((theFolder as string) & "words.txt")
set nameArray to paragraphs of (read theFile as «class utf8»)
Something to keep in mind, if the last line in the file ends with a line feed then the last item in the list will be "" and you can either account for this in your code as you use each item of the list or add the following example to remove it if it exists:
if last item of nameArray is equal to "" then ¬
set nameArray to items 1 thru -2 of nameArray

Related

Combining two (applescript) scripts into one

I'm trying to simplify my workflow by combining the following two applescripts into one, they work fine separately but it'd be more efficient to combine them.
In short, script A trims a file name into the last 3 characters and Script B adds the folder name (where the files reside) to the file name.
This might be a very simple fix but I'm script-writing challenged so any help is welcomed.
SCRIPT A:
on open whichFile
repeat with aFile in whichFile
tell application "Finder"
set filename to name of aFile
set name of aFile to ((characters -1 thru -7 of filename) as string)
--set name of whichFile to ((characters 1 thru -4 of filename) as string) --trim last 3
end tell
end repeat
end open
SCRIPT B
on open theDroppedItems
repeat with a from 1 to length of theDroppedItems
set theCurrentDroppedItem to item a of theDroppedItems
set theCurrentDroppedItem to theCurrentDroppedItem as string
tell application "System Events"
set folderPath to theCurrentDroppedItem as string
--display dialog (folderPath)
set AppleScript's text item delimiters to ":"
set newFileName to (text item -4 of folderPath as string) & "-" & (text item -2 of folderPath as string) & "-" & (text item -1 of folderPath as string)
--display dialog (newFileName)
--rename file
set fileAlias to (theCurrentDroppedItem) as alias
set the name of fileAlias to newFileName
end tell
end repeat
end open
You can start by opening a new Script Editor document for the combined script. The open handler is passed a list of file items, so you can add a new handler declaration with an empty repeat statement that steps through the dropped items. From there, just identify the statements that perform the various operations (trim name, get folder name, etc), and copy them into the new open handler's repeat statement, editing as needed to use consistent variable names.
Once the new script is running, then you can look at optimizing it by combining and/or rearranging statements that may be doing the same thing in the different scripts. It can also be helpful to organize functions into their own handlers, such as the getNamePieces handler below. I also like to add a run handler with a choose file dialog so that you can test without having to drag items onto a droplet.
Note that the file name includes any extension, so you should break it apart in order to work with just the name part. There is also a bit of unnecessary thrashing about in the script that gets the folder name, so after cleaning it up your script could look something like:
on run
open (choose file with multiple selections allowed)
end run
on open droppedItems
repeat with anItem in droppedItems
set {folderPath, theName, extension} to getNamePieces from anItem
set trimmedName to text -1 thru -3 of theName -- work with just the name part
tell application "System Events"
set folderName to name of disk item folderPath
set newName to folderName & "-" & trimmedName & extension -- assemble the pieces
log newName -- for testing
# set name of anItem to newName -- uncomment to go live
end tell
end repeat
end open
to getNamePieces from someItem -- return the containing folder path, the name, and the extension
tell application "System Events" to tell disk item (someItem as text)
set theContainer to path of the container
set {theName, extension} to {name, name extension}
end tell
if extension is not "" then
set theName to text 1 thru -((count extension) + 2) of theName -- just the name part
set extension to "." & extension
end if
return {theContainer, theName, extension}
end getNamePieces

Merging files in Applescript

I am trying to do below in AppleScript.
Concatenate/Merge all *.xxx files found in a particular folder into one new file
Each file contains a header. Strip header from all but 1st file before merging.
Add a footer text to the merged file.
This sounds relatively simple in other languages but I am a beginner to applescript. Any help to find a direction would be appreciated.
TIA
AnuRV
Try this, you are prompted to choose a base folder and a destination file name.
Important: Use a destination location outside the base folder to avoid the file to be included in the merging process.
I assume that your tsv file type is a typo and you mean csv.
If not, change all occurrences of csv in the script.
The text delimiter is linefeed (0A), if you need return (0D) change the occurrence of linefeed to return.
set baseFolder to choose folder
set destinationFile to choose file name with prompt "Choose destination file name" default name "merged.csv"
tell application "Finder" to set tsvFiles to (files of baseFolder whose name extension is "csv") as alias list
set text item delimiters to linefeed
try
set fileDescriptor to open for access destinationFile with write permission
repeat with i from 1 to (count tsvFiles)
set theFile to item i of tsvFiles
set theText to paragraphs of (read theFile as «class utf8»)
if i = 1 then
write (theText as text) to fileDescriptor as «class utf8»
else
write ((items 2 thru -1 of theText) as text) to fileDescriptor as «class utf8»
end if
end repeat
close access fileDescriptor
on error
try
close destinationFile
end try
end try
set text item delimiters to {""}

Error message on Applescript duplicate and rename

I use this applescript to Archive episodes to a new location using a smal reference-file "Archived.m4v" which is then renamed to the episodes name.
I keep getting an error message in OSX Yosemite, while under OSX Mavericks it worked perfectly.
error "The variable NewFile is not defined." number -2753 from "NewFile"
All questions related to a script like this have the same code, so I'm going nuts here...
set TheFile to alias "Video:Tools:Archived.m4v"
set Destination to alias "Video:Archives:WIP - TV Shows:"}
set Source to (choose folder with prompt "Pick the folder with the tv episodes...")
tell application "Finder"
set theList to every file of entire contents of Source
repeat with thisFile in theList
set {tid, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "."}
set FileName to (text items 1 thru -2 of (get name of thisFile)) as text
set NewFile to duplicate TheFile to folder Destination with replacing
set NewFile's name to (FileName & ".m4v")
end repeat
end tell
The only obvious mistake I see is in your duplicate line. Destination is already an alias so it should not have the word "folder" in front of it. I can't test this right now but try removing "folder" and see if that helps.
The only other thing to try if that didn't fix it is to change your last line to...
set name of file ((destination as text) & "Archive.m4v") to (FileName & ".m4v")

Reading file in AppleScript

I'm trying to read an html file into a variable in AppleScript, I have the following code.
tell application "Finder"
set theItems to every file of folder folderName
repeat with theFile in theItems
open for access theFile
set fileContents to (read theFile)
end repeat
end tell
Now I get an error like:
Finder got an error: Can’t make document file "index.html" of folder
[...] of startup disk into type «class fsrf».
What am I doing wrong? I followed this example. Are HTML files not recognized as text?
You have to convert the Finder file objects to aliases or text.
read can be used without separate open or close commands. It reads files as MacRoman without as «class utf8» though. (as Unicode text is UTF-16.)
tell application "Finder" to files of folder "HD:Users:lauri:Sites" as alias list
repeat with f in result
read f as «class utf8»
end repeat
Try:
tell application "Finder" to set theItems to every file of folder folderName
repeat with theFile in theItems
set aFile to POSIX path of (theFile as text)
set fileContents to do shell script "cat " & quoted form of aFile
end repeat
Starting from your original code, this should do it:
set folderPath to choose folder
set someData to ""
tell application "Finder"
set theItems to every file of folder folderPath as list
repeat with theFile in theItems
set theFilePath to theFile as text
if characters -5 thru -1 of theFilePath as string is ".html" then
set theFileHandle to (open for access file theFilePath)
set fileContents to (read theFileHandle)
-- for testing, call some function
set someData to someData & return & processHtml(fileContents) of me
close access theFileHandle
end if
end repeat
-- do something with someData here
return someData
end tell
on processHtml(theData)
-- do something with theData here
return theData
end processHtml
As Lauri wrote, you can add "as «class utf8»" to read the file as UTF8. You could also use "as Unicode text" for UTF16. Personally, I like this, because it is vanilla AppleScript and doesn't need shell scripting.
Using open for access is really doing it the hard way.
If you want to read an HTML file with AppleScript, then the best way to do that is to use AppleScript to tell an HTML editor to read the HTML file for you. That is the fundamental way that AppleScript works. That’s why “tell” is the most important command. That’s why you can accomplish your goal of reading an HTML file into a variable in just 3 lines:
tell application "BBEdit"
open (choose file)
set theHTMLSource to the text of document 1
close document 1
end tell
The following script expands on the above to read an arbitrary number of HTML files from a chosen folder. It works with BBEdit 9, and should also work with BBEdit’s free version, which is called “TextWrangler” and is available in Mac App Store. Or you can fairly easily adapt this script for use with HyperEdit or TextEdit or whatever AppleScript-aware HTML/text editor you prefer to use.
tell application "Finder"
set theFolder to (choose folder)
set theFiles to every file of folder theFolder
set theHTMLSourceList to {}
repeat with theFile in theFiles
if the kind of theFile is equal to "HTML document" then
set theName to the name of theFile
tell application "BBEdit"
open file (theFile as text)
set theSource to the text of document 1
copy {theName, theSource} to the end of theHTMLSourceList
close document 1
end tell
end if
end repeat
end tell
When the above script is finished, the variable “theHTMLSourceList” is populated with the names and source code of the entire folder of HTML documents, like so:
{{name of file 1, source of file 1}, {name of file 2, source of file 2}, {name of file 3, source of file 3}}
… and so on up to an arbitrary number of files. But of course you can have the script return the HTML source to you in whatever way you like. The key point is that an AppleScript-aware HTML editor can both read HTML and set AppleScript variables, so you don’t have to write (and debug and maintain) your own HTML reader in tiny AppleScript.

How find the file name of an executing AppleScript

How do I find the name of an executing AppleScript?
REASON: I want to create a script that changes its behavior based on its filename. Something like:
if myname is "Joe" then ACTION1
else if myname is "Frank" then ACTION2
else ACTION3
The normal way to get the name is by using "name of me". However applescripts are run by applescript runner so when you use that on a script you get "Applescript Runner" as the name. If you compile your script as an application then "name of me" will work. The only way to get the script name is by getting its path and extracting the name. Something like this would thus work for scripts...
getMyName()
tell me to display dialog result
on getMyName()
set myPath to path to me as text
if myPath ends with ":" then
set n to -2
else
set n to -1
end if
set AppleScript's text item delimiters to ":"
set myName to text item n of myPath
if (myName contains ".") then
set AppleScript's text item delimiters to "."
set myName to text 1 thru text item -2 of myName
end if
set AppleScript's text item delimiters to ""
return myName
end getMyName
Here's a method that works for all of the following:
*.scpt files (compiled AppleScript files; run in AppleScript Editor or with osascript)
*.applescript files (uncompiled AppleScript files; run in AppleScript Editor or with osascript)
command-line scripts that directly contain AppleScript (marked as executable and starting with #!/usr/bin/env osascript):
*.app files created with AppleScript Editor
*.app files created with Automator that contain AppleScript actions
Note: By contrast, it does not work for the following:
OS X services created with Automator that contain AppleScript actions (special *.workflow files) - always reports 'WorkflowServiceRunner[.xpc]'
general-purpose *.workflow files created with Automator that contain ApplesScript actions and that are run with automator - always reports 'Automator Runner[.app]'
Get the name of the running script, including filename extension (.scpt, .app, or .applescript, as the case may be):
tell application "System Events" to set myname to get name of (path to me)
If you want to remove the filename extension with a single command, use the following, do shell script-based approach:
tell application "System Events" to set myname to do shell script "rawName=" & quoted form of (get name of (path to me)) & "; printf '%s' \"${rawName%.*}\""
Here's an all-AppleScript alternative that is more verbose (yet concise by AppleScript standards):
tell application "System Events"
set myname to name of (path to me)
set extension to name extension of (path to me)
end tell
if length of extension > 0 then
# Make sure that `text item delimiters` has its default value here.
set myname to items 1 through -(2 + (length of extension)) of myname as text
end if
Finally, here's a variation: a subroutine that you can call with set myname to getMyName():
on getMyName()
local myName, tidSaved
tell application "System Events"
set myAlias to path to me -- alias to the file/bundle of the running script
set myName to name of myAlias -- filename with extension, if any.
if name extension of myAlias is not "" then -- strip away extension
set {tidSaved, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {""}}
set myName to items 1 through -(2 + (length of (get name extension of myAlias))) of myName as text
set AppleScript's text item delimiters to tidSaved
end if
end tell
return myName
end getMyName
An easier way to find out the base part of the path is using name of:
tell application "Finder"
set p to path to me
set nam to name of file p as text
end tell
Maybe this:
set appname to name of current application

Resources