Keep getting errors trying to create and write to file

I’m trying to create a new file and write some text to it. If the file already exists I just need to write the text to that file. The following code works:

set newFile to POSIX file "Users/[home]/Desktop/BrandNewFile.txt"
set referenceNumber to open for access newFile with write permission
write "It works again" & return to newFile starting at eof
close access referenceNumber

But, what I really need is to have this as the first line:

set newFile to path to desktop & "BrandNewFile.txt"

But, that returns a list type variable which can’t be turned into a file. I’ve tried every combination of type coercion I can think of: alias, string, file etc. with brackets in various places. Sometimes, it successfully concatenates into a string or alias but then I get errors in either the open for access or write statements.

I guess my main problem is how to force two variables to concatenate successfully then turn into a type that can be a new/existing file that is opened and written to.

I’ve spent hours reading posts here and other places but, nothing works for me – probably because I just don’t get it.

Thanks.

set newFile to ((path to desktop as text) & "BrandNewFile.txt") as «class furl»

Hi.

When you use open for access, you should address all subsequent Read/Write actions on the file to the returned reference number, not to the file itself. This is both more efficient and safer, because it’s possible to have more than one access channel open to the same file at the same time (although only one can have write permission). You should also put the actions in a try statement, so that any problems which occur while the channel’s open don’t crash the script before it can close the channel again.

set newFile to ((path to desktop as text) & "BrandNewFile.txt") as «class furl» -- Shane's line.
set referenceNumber to (open for access newFile with write permission)
try
	write "It works again" & return to referenceNumber starting at eof -- not 'to newFile'.
	close access referenceNumber
on error errMsg
	close access referenceNumber
	display dialog errMsg
end try

Shane, Nigel, many thanks.

I woke up this morning with a clearer head and tried a new idea which works. Basically, I separated out every coercion into a separate statement with explicit coercion (eg. “as string”) and also changed the write statement to address the file reference instead of the file. So, it now works.

But, I’ve not seen the “as «class furl»” before. I’ll get out my copy of Everyday AppleScriptObjC !

Cheers.

File URLs pre-date ASObjC, but they mostly travel incognito:

set x to choose file name
class of x