Error while wrting data into file using Applescript - applescript

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.

Related

How to write a txt file and duplicate it, and have it be able to run on any computer with different users?

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

AppleScript Image Events cant get class asDB

Wanting to learn more about Mac's Image Events I am trying to learn how to save a file from one type into another type. For example, if I have a BMP image named foobar.bmp I wanted to learn how to save it out as foobar.jpg but in my handler I get an error:
Image Events got an error: Can’t get «class asDB» id (application
"Image Events") of image "foobar.bmp".
My code inside my handler:
tell application "Finder"
set directory to (choose folder with prompt "Please select a directory.")
set someImages to (files of folder directory where name extension is "bmp") as alias list
repeat with someImage in someImages
tell application "Image Events"
launch
set workingImage to open someImage
save workingImage as JPEG in directory
close workingImage
end tell
end repeat
end tell
I did test to see if the save may need the POSIX Path instead of the Alias Path with:
set directoryPosix to (POSIX path of directory)
and changed the save:
save workingImage as JPEG in directoryPosix
but I am still producing the same error and I dont understand why. The code works but just throws an error and after searching I am unable to find a resolution. I already know how to do this with Bash using ImageMagick and I could do this using AppleScript and SIPs but I would like to learn more about Image Events. What am I doing wrong to throw the error? If it helps my OS is up-to-date and running Yosemite version 10.10.5.
You need to specify the full (HFS or POSIX) path of the new file rather than the alias specifier to the destination folder:
set directory to (choose folder with prompt "Please select a directory.") as text
tell application "Finder" to set someImages to (files of folder directory where name extension is "bmp") as alias list
tell application "Image Events"
launch
repeat with someImage in someImages
set workingImage to open someImage
set fileName to name of workingImage
set newFilePath to directory & text 1 thru -4 of fileName & "jpg"
save workingImage as JPEG in newFilePath
close workingImage
end repeat
end tell

AppleScript how to write a file path to a text file

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

Why does this applescript that tasks to iTunes sometimes fail with -1712

I have some applescript for creating a list of the fiels under iTunes control and writing it to a file, this is the complete script:
tell application "iTunes"
if (count of every file track of library playlist 1) is equal to 0 then
set thePath to (POSIX file "/tmp/songkong_itunes_model.txt")
set fileref to open for access (thePath) with write permission
set eof fileref to 0
return
end if
tell every file track of library playlist 1
script performancekludge
property tracknames : its name
property locs : its location
property persistids : its persistent ID
end script
end tell
end tell
set thePath to (POSIX file "/tmp/songkong_itunes_model.txt")
set fileref to open for access (thePath) with write permission
set eof fileref to 0
tell performancekludge
repeat with i from 1 to length of its tracknames
try
set nextline to item i of its tracknames ¬
& "::" & POSIX path of item i of its locs ¬
& "::" & item i of its persistids
write nextline & linefeed as «class utf8» to fileref
end try
end repeat
end tell
close access fileref
and sometimes it gives
create_itunes_model.scpt:428:436: execution error: iTunes got an error: AppleEvent timed out. (-1712)
for some users, but I dont know why
Does anybody know why, or how I could improve my script
First you should close access fileref before your first return. Otherwise the text file could stay in an opened state.
The error looks like a timeout if the user's iTunes Library is too big and the script takes too much time to run. You should use a with timeout-block:
with timeout of 600 seconds
-- your script here
end timeout
Have fun, Michael / Hamburg

How can I create or replace a file using Applescript?

I'm trying to write content to a file, /tmp/test.txt with AppleScript.
If the file doesn't exist, I want to create it.
If it does exist, I want to replace the contents.
This is proving quite difficult because AppleScript has a different syntax for creating a new file versus writing to an existing file. I also thought about deleting a file if it already exists, and then creating it, but AppleScript will move things to the trash by default and so even that is rather complicated.
The data I am going to write to the file may have a lot of special characters in it, so I don't really want to do something like do shell script "cat " + data + " > /tmp/txt.txt" because I am unaware of any escapeshellarg for AppleScript.
Below is what I have so far but I'm getting an error:
Can't make file "Macintosh HD:private:tmp:test.txt" into type reference.
I would really like to abstract this by improving the helper function write_to_file that I got here so that it would take care of creating the file if it does not exist.
my write_to_file("hello", "/tmp/test.txt", false)
on write_to_file(this_data, target_file, append_data)
try
if not (exists POSIX file target_file) then
make new document file at ("/tmp/" as POSIX file as alias) with properties {name:"test.txt", text:the_data}
end if
set the target_file to the target_file as POSIX file
set the open_target_file to open for access file target_file with write permission
if append_data is false then set eof of the open_target_file to 0
write this_data to the open_target_file starting at eof
close access the open_target_file
return true
on error e
try
display dialog e
close access file target_file
end try
return false
end try
end write_to_file
How can I create or replace a file using Applescript?
The first mistake you've made is mixing POSIX paths with HFS paths. A posix path is /tmp/test.txt and a hfs path to the same file will be Macintosh HD:tmp:test.txt if the name of the boot volume is Macintosh HD of course.
open for access file "Volume:Path:to:file.txt"
The second mistake is that for Mac OS X the /tmp folder is not the place to store temporary files. You will need administrator privileges to write there and the user will be prompted for username and password. It is stored in /var/folders and there is a folder created at login for each user, also with fast user switching. To access the path to this folder you should use the command path to temporary items. Temporary items will be removed between startups.
set theFile to (path to temporary items as string) & "test.txt"
The third mistake is that when you're using quoted form of you can use do shell script. Since AppleScript is unicode like the shell there is no such thing as that characters can't be handled by do shell script.
do shell script "/bin/echo -n " & (quoted form of "$#%^&*()#") & " > " POSIX path of theFile
At last you've made the mistake that you need to check for existence of a file. When you're using open for access command the file will be created when it doesn't exists for you. So the only code you need is:
set theFile to (path to temporary items as text) & "test.txt"
writeToFile(theFile, "Hello!", false)
writeToFile(theFile, (linefeed & "Goodbye!" as string), true)
on writeToFile(p, d, a)
try
set fd to open for access file p with write permission
if not a then set eof of fd to 0
write d to fd starting at (get eof of fd) as «class utf8»
close access fd
on error
close access file p
end try
end writeToFile
or using a do shell script which creates an UTF-8 file as well but the given path needs to be an POSIX path now
set theFile to (path to temporary items as text) & "test.txt"
writeToFile(POSIX path of theFile, "goodbye!", false)
writeToFile(POSIX path of theFile, (linefeed & "hello!" as string), true)
on writeToFile(p, d, a)
set cmd to "/bin/echo -n " & quoted form of d & " >"
if a then set cmd to cmd & ">"
do shell script cmd & space & quoted form of p
end writeToFile
Choose the one to your likings
Try:
my write_to_file("hello", "/tmp/test.txt", true)
on write_to_file(this_data, target_file, append_data)
try
tell application "System Events" to exists file target_file
if not the result then do shell script "> " & quoted form of target_file
set the open_target_file to open for access target_file with write permission
if append_data is false then set eof of the open_target_file to 0
write this_data to the open_target_file starting at eof
close access the open_target_file
return true
on error e
try
display dialog e
close access target_file
end try
return false
end try
end write_to_file

Resources