textfile - writing to a file



set myfile to "/Users/Username/Desktop/file2.txt"
set theText2 to read myfile

set theText2 to theText2 as integer

set theText2 to theText2 +1


How would you write the variable theText2 to to file2.txt?

As I don’t like to reinvent the wheel, when I must write something in a text file I use a prewritten handler.

set myfile to (path to desktop as text) & "file2.txt"
set theText2 to read file myfile

set theText2 to theText2 as integer

set theText2 to theText2 + 1
my writeTo(myfile, theText2, text, false)

#=====
(*
Handler borrowed to Regulus6633 - http://macscripter.net/viewtopic.php?id=36861
*)
on writeTo(targetFile, theData, dataType, apendData)
	-- targetFile is the path to the file you want to write
	-- theData is the data you want in the file.
	-- dataType is the data type of theData and it can be text, list, record etc.
	-- apendData is true to append theData to the end of the current contents of the file or false to overwrite it
	try
		set targetFile to targetFile as «class furl»
		set openFile to open for access targetFile with write permission
		if not apendData then set eof of openFile to 0
		write theData to openFile starting at eof as dataType
		close access openFile
		return true
	on error
		try
			close access targetFile
		end try
		return false
	end try
end writeTo

#=====

Of course, if you dislike the use of handler you may use this bare code :

set myfile to (path to desktop as text) & "file2.txt"
set theText2 to read file myfile
set theText2 to theText2 as integer

set theText2 to theText2 + 1

write theText2 as text to file myfile # Don't remove the coercion as text !
read file myfile

Or, if you really need to use an unix path:

set myfile to (path to desktop as text) & "file2.txt"
set myfile to POSIX path of myfile
set theText2 to read myfile
set theText2 to theText2 as integer

set theText2 to theText2 + 1

write theText2 as text to myfile # Don't remove the coercion as text !
read myfile

Yvan KOENIG running El Capitan 10.11.4 in French (VALLAURIS, France) mardi 19 avril 2016 21:42:40

awesome thanks ivan exactly what I needed!!! saved me such a headache… :slight_smile: