Append Text to Text File in Applescript

Discussion in 'Mac Programming' started by BobRon, Mar 23, 2014.

  1. BobRon macrumors member

    Oct 13, 2012
    I have this applescript code that I need to be able to add text to the end of a .txt file. My current code is:
    set theFile to (POSIX file "/Library/Application Support/PWRSaver/exclude.txt")
    open for access theFile
    set fileContents to (read theFile)
    close access theFile
    tell application "TextEdit"
    	open "Library:Application Support:PWRSaver:exclude.txt"
    	set text of exclude to (fileContents & "hi")
    end tell
    It always gives me errors. Any Ideas?
  2. chown33 macrumors 604

    Aug 9, 2009
    What error does it give you? Be specific; post the exact text of the error message.

    There is a far simpler way of appending to a text file:
    do shell script "echo hi >>/Library/Application Support/PWRSaver/exclude.txt"
    If this doesn't work, then post the error message you get.

    If you need something other than "hi" appended to the file, then tell us exactly what you want appended. The 'do shell script' command follows the shell's rules for quoting, so if what you want appended contains certain characters, then you must use correct quoting.

    One reason it might not work would be the permissions on the target file. So if you get an error message, then copy and paste this into a Terminal window, then copy and paste the complete output into a reply here:
    ls -l /Library/Application Support/PWRSaver/exclude.txt
  3. kryten2, Mar 23, 2014
    Last edited: Mar 23, 2014

    kryten2 macrumors 6502a

    Mar 17, 2012
    The result of your first statement set theFile to ... is an HFS path, which takes the form "disk:item:subitem:subsubitem:...:item". For example, "" is the HFS path to the Mail application, assuming your boot drive is named "Hard_Disk". You don't need open for access and close access to read a file. Your open "Library:Application Support:pWRSaver:exclude.txt" statement is missing your boot drive.
    Look at the colors of your compiled script, especially the set text of exclude to statement. Is exclude a variable or subroutine? You haven't defined it so that will throw up an error as well.

    Example :

    set theFile to (POSIX file "/Library/Application Support/PWRSaver/exclude.txt")
    set fileContents to (read theFile)
    tell application "TextEdit"
    	--open "Library:Application Support:PWRSaver:exclude.txt"
    	set myDocument to open theFile
    	set text of myDocument to (fileContents & "hi")
    end tell

    Attached Files:

Share This Page