Writing to a text file

Hey,

I'm making a script that gets the names of all the songs in the itunes music library and prints them to a TextEdit file.  I've gotten it to get all the names I just don't know how to print the results to a textedit file.  :rolleyes:  There's probably a really obvious way to do it.  Any help would be great.

Thanks,
Matt

The AppleScript instruction “set fileRef to open for access fileOrAliasReference with write permission” will open an existing text file or create one of that name if it doesn’t exist. TextEdit will be able to open this file and the variable fleRef (or whatever you want to call it) will contain a reference to the file for later use.

Then when you’ve got your data in an expression you “write expression to fileRef” – the file reference returned in the open statement. You can add “for numberOfBytes”, “starting at integer” (starting at eof appends it to what’s there).

To erase an existing document [careful] you can “set eof to 0” before you write and that overwrites whatever was there.

Oops - forgot:

Before leaving your script, be sure to “close access fileRef” or you’ll leave the file in use.

ok, I actually figured it out before you answered :slight_smile: I have another question though: is there any way to make each song appear on its own line. Right now it just puts all the songs one after the other in a hard to read mess :stuck_out_tongue: This is what applescript generates when it gets the songs from music library:

get name of every file track of playlist "library"
		{"Let Me Go", "When I'm Gone", "Away From the Sun", "The Road I'm On", "Ticket To Heaven", "Running Out Of Days", "Here Without You", "I Feel You", "Dangerous Game", "Changes", "Going Down In Flames"

and so on and so forth…I just need to print each song name on its own line to make it readable

Thanks again!

set Lib to {"Let Me Go", "When I'm Gone", "Away From the Sun", "The Road I'm On", "Ticket To Heaven", "Running Out Of Days", "Here Without You", "I Feel You", "Dangerous Game", "Changes", "Going Down In Flames"}

repeat with aName in Lib
	set contents of aName to contents of aName & return
end repeat
Lib

ahhh it worked…Thanks so much :cool:

If you just want paragraph delimited text that you can write to a file, you might consider using text item delimiters. On long lists, this approach can be significantly faster than looping through each item:

on listToParagraphs(l)
	set d to text item delimiters
	set text item delimiters to return
	tell l to set l to beginning & ({""} & rest)
	set text item delimiters to d
	l
end listToParagraphs

set currList to {"Let Me Go", "When I'm Gone", "Away From the Sun", "The Road I'm On", "Ticket To Heaven", "Running Out Of Days", "Here Without You", "I Feel You", "Dangerous Game", "Changes", "Going Down In Flames"}

listToParagraphs(currList)