Add text to file - script not working

Hello,

I have a script to add text at the beginning of a file which works when used with a single file, see below:

set the_file to choose file
set the_content to read of the_file

set the_new_stuff to "## " & the_content
set the_file_path to the_file as string
set open_for_writing to open for access file the_file_path with write permission
write the_new_stuff to open_for_writing starting at 0
close access open_for_writing

However, when I try to change this script to do this on all files into a folder as a batch, it does not work. I am doing something wrong but I do not know what, see below:

set the_file_path to choose folder
tell application "Finder" to set the_file to (files of the_file_path whose name extension is "txt") as alias list

try
	repeat with i from 1 to (count the_file)
		set the_content to read of the_file
		set the_new_stuff to "## " & the_content
		set the_file_path to the_file as string
		set open_for_writing to open for access file the_file_path with write permission
		write the_new_stuff to open_for_writing starting at 0
		close access open_for_writing
	end repeat
end try

Can someone help please.

Thanks in advances and regards
Henri

Hi Henri.

I’m guessing that the text in your files is in UTF-8 form:

set the_folder to (choose folder)
tell application "Finder" to set the_files to (files of the_folder whose name extension is "txt") as alias list

repeat with i from 1 to (count the_files)
	set this_file to item i of the_files
	set open_for_writing to (open for access this_file with write permission)
	try
		set the_content to (read open_for_writing as «class utf8»)
		set the_new_stuff to "## " & the_content
		set eof open_for_writing to 0
		write the_new_stuff to open_for_writing as «class utf8»
	end try
	close access open_for_writing
end repeat

Hi Nigel,

Thanks a lot, this works perfectly and yes my files are UTF-8.

Again thanks and have a nice day.

Regards
Henri