I'm trying to write a script that will convert .numbers
documents to .csv
documents. It needs to be executable from the command line so I can use it in a pre-commit git hook.
I've written an AppleScript to take a path to a numbers file and export it as CSV, but the actual exporting won't work because "You don’t have permission. (6)". I think this has to do with sandboxing, but I can't use AppleScript to pop up a file picker because this needs to be completely automated.
How can I give my AppleScript permissions to export to this file?
on run argv
set input_file to item 1 of argv
set output_file to input_file
--strip off the .numbers extention
set delims to AppleScript's text item delimiters
set AppleScript's text item delimiters to "."
if output_file contains "." then set output_file to (text items 1 thru -2 of output_file) as text
-- set the extension to be csv
set output_file to output_file & ".csv"
set output_file to POSIX file output_file
tell application "Numbers"
activate
tell (open input_file)
set activeDocument to it
with timeout of 3 seconds
export activeDocument as CSV to output_file
end timeout
close activeDocument saving yes
end tell
end tell
end run
The full error message is
export_numbers_to_csv.scpt:604:676: execution error: Numbers got an error: The document “DisplayPlusButtonTestScripts.numbers” could not be exported as “DisplayPlusButtonTestScripts”. You don’t have permission. (6)
My invocation is osascript export_numbers_to_csv.scpt /Users/me/Test\ Scripts/MyTests.numbers
from the working directory /Users/me/
.
I do have permissions to write to the directory I am asking the script to write to. I also tried exporting to a temporary directory (via the path to temporary items from user domain
) but got the same error message.
Permissions can get messy if a .csv file has already existed in the same directory and with the same name as the one you're trying to export to. If you created that .csv file or at least edited/opened it at some point, then you'll have permission to export to that name, but if it's never been opened for write access on your machine before (for example if you downloaded it), then the necessary permissions won't be there.
To get around this, you can add the following lines to your script before the 'tell application "Numbers"' block:
This tells the script to open the file for write access, and since it only needs to be opened to get the necessary permissions, it then closes it.