Tuesday, May 11, 2021

#1 2021-03-23 08:14:14 am

peavine
Member
From:: Prescott, Arizona
Registered: 2018-09-04
Posts: 872

Appending text to a file

I occasionally need to append text to a file and expected to be able to do this with a single write command. However, reading the documentation and some Google research yielded nothing.

I've included below my temporary solution, which is to read the file, append the text, and then write the original and appended text to the file. This works and is reasonably quick but I wondered if there's a simpler solution. Right now, the total amount of text almost never exceeds 50 lines but that might change in some future script. Thanks.

Applescript:

use framework "Foundation"
use scripting additions

on appendToFile(theFile, textToAppend)
   set theText to current application's NSString's stringWithContentsOfFile:theFile encoding:(current application's NSUTF8StringEncoding) |error|:(missing value)
   if theText is missing value then return false
   set theText to theText's stringByAppendingString:textToAppend
   
   set theResult to (current application's NSString's stringWithString:theText)'s writeToFile:theFile atomically:true encoding:(current application's NSUTF8StringEncoding) |error|:(missing value)
end appendToFile

set theFile to POSIX path of ((path to desktop as text) & "Test File.txt")
set textToAppend to "A New Line" & linefeed

appendToFile(theFile, textToAppend)

Last edited by peavine (2021-03-23 09:14:15 am)


2018 Mac mini - macOS Catalina

Offline

 

#2 2021-03-23 09:23:14 am

StefanK
Member
From:: St. Gallen, Switzerland
Registered: 2006-10-21
Posts: 11746
Website

Re: Appending text to a file

The usual ObjC way is first to check if the file exists. If not create it with the given text otherwise append the text with the NSFileHandle API. It's actually the same procedure as AppleScript's write ... starting at eof

Applescript:

use AppleScript version "2.5"
use framework "Foundation"
use scripting additions

property |⌘| : a reference to current application

on appendText from textToAppend into theFile
   set fm to |⌘|'s NSFileManager's defaultManager()
   set textData to (|⌘|'s NSString's stringWithString:textToAppend)'s dataUsingEncoding:(|⌘|'s NSUTF8StringEncoding)
   if not (fm's fileExistsAtPath:theFile) as boolean then
       return (fm's createFileAtPath:theFile |contents|:textData attributes:(missing value)) as boolean
   else
       set logFileHandle to |⌘|'s NSFileHandle's fileHandleForWritingAtPath:theFile
       logFileHandle's seekToEndOfFile()
       logFileHandle's writeData:textData
       logFileHandle's closeFile()
       return true
   end if
end appendText


set theFile to POSIX path of (path to desktop) & "Test File.txt"
set textToAppend to "A New Line" & linefeed

appendText from textToAppend into theFile

Last edited by StefanK (2021-03-23 09:24:34 am)


regards

Stefan

Offline

 

#3 2021-03-23 10:03:21 am

peavine
Member
From:: Prescott, Arizona
Registered: 2018-09-04
Posts: 872

Re: Appending text to a file

Thanks Stefan--that's excellent. NSFileHandle is entirely new to me, so I'll spend some time with that.

FWIW, I ran some two timing tests with your ASObjC suggestion and with AppleScript's write command.  The first timing test was with no existing text file and the second was with an existing 50-line text file. In every case, the timing result was 5 to 6 milliseconds, which is great. I've pretty much switched my scripts to use ASObjC but it's good to have choices.

Last edited by peavine (2021-03-23 10:46:54 am)


2018 Mac mini - macOS Catalina

Offline

 

#4 2021-03-24 09:31:46 am

peavine
Member
From:: Prescott, Arizona
Registered: 2018-09-04
Posts: 872

Re: Appending text to a file

I've been studying the NSFileHandle class, which raised a question, in that two of the commands in Stefan's script are deprecated. The writeData command was replaced with writeData:error, which is an easy change. However, closeFile has not been replaced with anything I could ascertain (except possibly closeAndReturnError).

I've already put Stefan's script to work in several of my scripts and everything works great. However, I noticed that the documentation for the fileHandleForWritingAtPath method contains the following and I wondered what happens when closeFile no longer works.

When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it.



The documentation for the closeFile method is at:

https://developer.apple.com/documentati … -closefile

Last edited by peavine (2021-03-24 09:52:41 am)


2018 Mac mini - macOS Catalina

Offline

 

#5 2021-03-24 01:02:28 pm

Fredrik71
Member
Registered: 2019-10-23
Posts: 707

Re: Appending text to a file

@peavine
I think you could use this method: initWithFileDescriptor:closeOnDealloc: and pass YES

You could read that on the link in your post

Last edited by Fredrik71 (2021-03-24 01:06:14 pm)


if you are the expert, who will you call if its not your imagination.

Online

 

#6 2021-03-24 05:33:52 pm

Shane Stanley
Member
From:: Australia
Registered: 2002-12-07
Posts: 6628

Re: Appending text to a file

peavine wrote:

I've been studying the NSFileHandle class, which raised a question, in that two of the commands in Stefan's script are deprecated.



The term deprecated can have a range of meanings -- here it's probably closer to a nudge.

The method changes are a (belated) effort to ensure that methods that can fail return (hopefully meaningful) errors when they do. However, unless you're writing code that actually uses these errors, it's a bit pointless.

Perhaps more to the point, the new methods are only available in macOS 10.15 and later, which is a pretty severe restriction for a lot of people.

However, closeFile has not been replaced with anything I could ascertain (except possibly closeAndReturnError).



It is indeed closeAndReturnError:.

However, I noticed that the documentation for the fileHandleForWritingAtPath method contains the following and I wondered what happens when closeFile no longer works.



I suspect that's not going to happen for a long, long time, if ever.


Shane Stanley <sstanley@myriad-com.com.au>
www.macosxautomation.com/applescript/apps/
latenightsw.com

Offline

 

#7 2021-03-24 06:17:49 pm

peavine
Member
From:: Prescott, Arizona
Registered: 2018-09-04
Posts: 872

Re: Appending text to a file

Shane Stanley wrote:

Perhaps more to the point, the new methods are only available in macOS 10.15 and later, which is a pretty severe restriction for a lot of people.



Thanks Shane for the great information. I hadn't considered the above-quoted point, which is certainly important for anyone participating in this forum. I've never given any consideration to the "Availability" column in the documentation, but I'll pay more attention to that in the future.

Last edited by peavine (2021-03-25 07:01:53 am)


2018 Mac mini - macOS Catalina

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)