I'm at near the end of building a new feature for my AppleScript.
I'm looking to be able to prompt the user to select an Excel file and then process that Excel File.
The new feature is that I want to store the file path of the file the user last selected so that the next time the script is executed the dialog box opens to the same folder.
I've got my dialog box working and I also have the file write piece working.
My issue is that I want to be able to write the file path to the text file and I don't know how.
Consider the following code:
set theFile to choose file with prompt "Please choose a file:" of type {"XLSX", "APPL"}
display dialog (theFile as string)
set outputFile to (("Macintosh HD:Users:lowken:Documents:") & "LaunchAgent_Alert.txt")
try
set fileReference to open for access file outputFile with write permission
write theFile to fileReference
close access fileReference
on error
try
close access file outputFile
end try
end try
The code works, however I'm getting garbage in the output file:
>Macintosh HDÀ·q†H+÷œMiamieMasterMind.xlsxó∑èœÇäRXLSXXCELˇˇˇˇI À·©‡œÇ¬í,MiamieMasterMind.xlsxMacintosh HD*Users/lowken/Dropbox/MiamieMasterMind.xlsx/
ˇˇ
My guess is that either I have a file encoding issue or I need to output the file path from theFile.
Your help is appreciated.
Usage of property explained by Craig is the easiest solution.
The property values will be reset in case you recompile the script.
However, if you really need to store the path value in txt file for use by other scripts, you just need to write the file, not as alias, but as string :
write (theFile as string) to fileReference
Of course, when reading the text file later, remember it is a string and not an alias !
Try using a property, and the script will do all the work for you:
property theContainer : null
property theFile : null
set theFile to choose file with prompt "Please choose a file:" of type {"XLSX", "APPL"}
tell application "Finder" to set theContainer to theFile's container
From the AppleScript Language Guide:
The value of a property persists after the script in which the
property is defined has been run. Thus, the value of currentCount is 0
the first time this script is run, 1 the next time it is run, and so
on. The property’s current value is saved with the script object and
is not reset to 0 until the script is recompiled—that is, modified and
then run again, saved, or checked for syntax.
You can save an appleScript’s class and read it as (the type class).
Examples
write theFile to fileReference — theFile is an appleScript’s alias
read it like this —> set theFile to read file "Macintosh
HD:Users:lowken:Documents:LaunchAgent_Alert.txt" as alias
If you save a list:
write myList to fileReference — myList is an
appleScript’s list
read it like this —> set myList to read file "Macintosh
HD:Users:lowken:Documents:LaunchAgent_Alert.txt" as list
If you save a record —> {b: "15", c:"éèà"} :
write myRecord to fileReference — myRecord is an appleScript’s
record
read it like this —> set myRecord to read file "Macintosh
HD:Users:lowken:Documents:LaunchAgent_Alert.txt" as record
If you save a real —> 200.123 :
write floatNumber to fileReference — floatNumber is an appleScript’s
number
read it like this —> set floatNumber to read file "Macintosh
HD:Users:lowken:Documents:LaunchAgent_Alert.txt" as real
If you save an integer —> 20099 :
write xNum to fileReference — xNum is an appleScript’s integer
read it like this —> set xNum to read file "Macintosh
HD:Users:lowken:Documents:LaunchAgent_Alert.txt" as integer
If you save a string —> "éèà:376rrrr" :
write t to fileReference — t is an appleScript’s string
read it like this —> set t to read file "Macintosh
HD:Users:lowken:Documents:LaunchAgent_Alert.txt" as string
Important : set eof to 0 before writing a new contents to an existing file
set fileReference to open for access file outputFile with write permission
set eof fileReference to 0
write something to fileReference
close access fileReference
Related
I am trying to create a script that can create a text file with random information, and then duplicate the file onto any computer's desktop. Therefore, I might need a way of reading a user's directory.
This AppleScript code works for me using the latest version of macOS Mojave.
property fileName : "Test Document.txt" --value can be changed
property theText : "Random Information" --value can be changed
writeToAFile()
on writeToAFile()
set theFile to (path to desktop as text) & fileName
set theFile to POSIX path of theFile
try
set writeToFile to open for access theFile with write permission
write theText & linefeed to writeToFile as text starting at eof
close access theFile
on error errMsg number errNum
close access theFile
set writeToFile to open for access theFile with write permission
write theText & linefeed to writeToFile as text starting at eof
close access theFile
end try
end writeToAFile
I am new to using applescript. I would like to write a script to add text to an existing file. Specifically, I would like to prepend/append a given document, e.g., prepend "Hello" [existing text in document] append "Goodbye." I found this example:
tell application "TextEdit"
activate
set theDesktopPath to the path to the desktop folder as text
set file_URLs_content to "HEEEELLOOOOOO"
make new document with properties {text:file_URLs_content}
save document 1 in file (theDesktopPath & "file.txt")
close document 1
end tell
But, this is not quite right because I do not need a new document, and I want to specify the location of the text (at the beginning of the file, or at the end).
I am open to other solutions, as well. Ultimately, I want to use the dictation command feature to run the script, perhaps via automator. Many thanks for your time!
TextEdit is not needed to write plain text to disk.
writeToDisk from theText into thePath given append:append writes plain text to disk
Parameters:
• theFile: a HFS path
• theText the text to be written
• with append: append the text - without append: overwrite from the beginning of the text
set theFile to (path to desktop as text) & "file.txt"
set file_URLs_content to "HEEEELLOOOOOO"
writeToDisk from file_URLs_content into theFile with append
on writeToDisk from theText into thePath given append:append
try
set fileDescriptor to open for access file thePath with write permission
if not append then set eof of fileDescriptor to 0
write theText to fileDescriptor
close access fileDescriptor
on error
try
close access file thePath
end try
end try
end writeToDisk
If you prefer to write UTF-8 encoded text change the write line into
write theText to fileDescriptor as «class utf8»
I'm trying to write in a TextEdit file already created.
The file is in rwxrwxrwx mode so no permission problem.
But when I execute my code, here is the error :
error "Network file permission error." number -5000 from file "/Users/me/Desktop/A directory/file.txt" to «class fsrf»
My code here :
-- Writing in the TextEdit file
set file_URLs_content to "HEEEELLOOOOOO"
tell application "TextEdit"
set theFile to "/Users/me/Desktop/A directory/file.txt"
set file_ref to (open for access file theFile with write permission)
set eof file_ref to 0
write file_URLs_content to file_ref
close access file_ref
end tell
And my file.txt is still empty, how can I avoid this error ?
The way you can avoid errors when writing text with TextEdit is to remember that it is a text editor. It already knows how to create and save text documents without generating errors. You don’t have to use (error-prone) open for access. You don’t have to use (error-prone) shell scripting. All you have to do is ask TextEdit to make you a text document with whatever contents you like and and save it wherever you like. TextEdit knows how to do that without generating file access errors (like open for access) or accidentally overwriting folders (like shell scripting.)
tell application "TextEdit"
activate
set theDesktopPath to the path to the desktop folder as text
set file_URLs_content to "HEEEELLOOOOOO"
make new document with properties {text:file_URLs_content}
save document 1 in file (theDesktopPath & "file.txt")
close document 1
end tell
The advantage of this method is it is faster and easier to write, it is less error-prone, the text file that you get as output has the same properties as text files that you create manually with TextEdit, and your script can now be easily expanded to include other apps. For example, the text content could come from another app or the clipboard, and the text file could be opened in another app or emailed after it is saved.
The most fundamental feature of AppleScript is sending messages to Mac apps in this way. If you want to convert a PNG to a JPEG, you don’t write a PNG decoder and JPEG encoder in AppleScript and open the PNG file for access and read it byte by byte and then encode a JPEG byte by byte. You simply tell Photoshop to open the PNG image and export it as a JPEG to a particular file location. The “open for access” command is a last resort for reading and writing files that you simply don’t have an app to read or write. The “do shell script” command is for incorporating command-line apps when you simply don’t have a Mac app to do the job, for example, you can do regex stuff with Perl. If all you are doing is working with text files, you not only have TextEdit, but you can also get the free TextWrangler from Mac App Store and it has a giant AppleScript dictionary for reading, writing, and editing text files.
You don't need TextEdit for that. Try this:
set the logFile to ((path to desktop) as text) & "log.txt"
set the logText to "This is a text that should be written into the file"
try
open for access file the logFile with write permission
write (logText & return) to file the logFile starting at eof
close access file the logFile
on error
try
close access file the logFile
end try
end try
Try:
set file_URLs_content to "HEEEELLOOOOOO"
set filePath to POSIX path of (path to desktop as text) & "file.txt"
do shell script "echo " & quoted form of file_URLs_content & " > " & quoted form of filePath
How do I remove passwords from multiple PDF files using Applescript or by creating a Workflow in OS X?
My scenario is that I have multiple password protected PDF files in a folder. I know the passwords for all, which is same. I want to be able to run a Workflow on this folder so that all PDFs inside it are unlocked by the workflow.
OR run an Applescript shell code on all these files at once
I also preferably want to be able to create a way where putting / moving / pasting any PDF in the folder automatically unlocks it :)
Help appreciated !!
Update:
I have tried pdftk. The following code works awesome in Terminal, once pdftk is installed
pdftk secured.pdf input_pw foopass output unsecured.pdf
Now I want to be able to create a workflow that runs this command on selected files or on all the files in a folder
The AppleScript command to execute a shell script is do shell script...
So something like this:
do shell script "pdftk secured.pdf input_pw foopass output unsecured.pdf"
should work.
At this point I see 2 options:
write an AppleScript script that ask the user for the folder or get it from the Finder selection and then execute the command for each file in the folder;
write an Automator workflow that get the files from the folder using already available actions and then attach a new action that execute the AppleScript script.
For option 2 you can set an Automator workflow as in the following image.
Have you heard of "Folder Actions"? It's a way to attach an applescript to a folder so that whenever a new file is added to the folder the applescript is run. A quick google search turned up this which will give you directions on how to set it up. You can do more google searching if you still have questions.
Here's an applescript you can use with folder actions. I didn't test it but it should work (it's basic code). This will do its stuff on only pdf files. Other files you add to the folder will be left alone. NOTE: you have to put in your values for the first 4 variables of the script.
Good luck.
on adding folder items to theFolder after receiving theItems
-- enter your values here
set pdftkPosixPath to "/usr/bin/pdftk"
set pWord to "foopass"
set appendedName to "_unlocked" -- text to append to the file name
set shouldTrash to true -- true or false, move the locked file to the trash after unlocking?
set fContainer to theFolder as text
repeat with anItem in theItems
try
tell application "System Events"
set fName to name of anItem
set fExt to name extension of anItem
end tell
if fExt is "pdf" and fName does not contain appendedName then
set baseName to (text 1 thru -5 of fName) & appendedName & ".pdf"
set newPath to fContainer & baseName
do shell script (quoted form of pdftkPosixPath & space & quoted form of POSIX path of anItem & " input_pw " & quoted form of pWord & " output " & quoted form of POSIX path of newPath)
if shouldTrash then
tell application "Finder" to move anItem to trash
end if
end if
end try
end repeat
end adding folder items to
EDIT: here's how you can ask for a password. Note that if you want to see the text then remove "with hidden answer".
display dialog "Enter a password:" default answer "" with icon note with hidden answer
set theAnswer to text returned of the result
if theAnswer is not "" then set pWord to theAnswer
am using the below script for writing the file, but sometimes am getting errors like mentioned below, pls suggest..
set filepath to POSIX path of "Macintosh HD:Library:Application Support:Macromedia:mms.cfg"
try
tell application "System Events"
if file filepath exists then
set myFile to open for access file filepath with write permission
set fileData to read myFile
set eof myFile to 0
write "blah blah" to myFile
close access myFile
else
return "File Not Found"
end if
end tell
on error
return false
end try
Error:
"Network file permission error." number -5000 from file "Macintosh HD:Library:Application Support:Macromedia:mms.cfg"
Also some times i will get this error, am unable to close the opened file
"File file Macintosh HD:Library:Application Support:Macromedia:mms.cfg is already open." number -49 from file "Macintosh HD:Library:Application Support:Macromedia:mms.cfg"
When i tried to close the ofile am getting this eror:
on openAFile(filepath)
try
set fp to open for access filepath with write permission
on error errstr number errNum
if errNum = -49 then
close access filepath
set fp to open for access filepath with write permission
else
display dialog errstr
return false
end if
end try
return fp
end openAFile
set pointer to openAFile("Macintosh HD:Library:Application Support:Macromedia:mms.cfg"
set fileContents to read pointer
Error
"Can’t make \"Macintosh HD:Library:Application Support:Macromedia:mms.cfg\" into type file." number -1700 from "Macintosh HD:Library:Application Support:Macromedia:mms.cfg" to file
I cannot explain the "Network file permission error" that you are receiving.
The "File file Macintosh HD:Library:Application Support:Macromedia:mms.cfg is already open." error happens when you script stops in the Script Editor without closing the file. This happens if there is some other logic error that prevents AppleScript from reaching the close access command in your on error block (or you press the Stop button at an inopportune time). Apple's AppleScript Editor does not close leaked file references for you when a script stops.
Your workaround of trying to close the file before opening it may work, but you are passing a string rather than a file or alias for the filepath. Use open for access file filepath and close access file filepath.