Haveing difficulty with simple increment

I have some code to increment a number in a text field by 1

but when i try and have say


in the txt originally and i +1 the number doesn’t go

002 but 101

the code is:

set DVDNumber to read file "Shared G4 HD:Users:karrenmay:Desktop:from CD/DVD - uploaded:DVD's:DVDIncrementNumber.txt"
set nxtDVD to DVDNumber
set nxtDVD to ((DVDNumber) + 1)

my incrementFile("" & nxtDVD & "", "Shared G4 HD:Users:karrenmay:Desktop:from CD/DVD - uploaded:DVD's:DVDIncrementNumber.txt", true)

on incrementFile(thisdata, targetfile, appenddata)
		set the targetfile to the targetfile as text
		set the opentargetfile to ¬
			open for access file targetfile with write permission
		if appenddata is false then ¬
			set eof of the opentargetfile to 0
		write thisdata to the opentargetfile --starting at eof
		close access the opentargetfile
		return true
	on error
			close access file targetfile
		end try
		return false
	end try
end incrementFile

I cant seem to bedugg it, have tried a fair few things.

Your problem is a combination of coercion between strings and integers, and the way ‘write’ works.

In the first place, when you read the file you’re reading in a string containing the three characters “001”.

Then you increment this by one. Since “001” is a string and you can’t add integers to strings, AppleScript coerces 001 to an integer and then adds 1, resulting in the integer value 2, not the string “002”.

When it comes to writing out the data, AppleScript writes the integer value 2 overwriting the existing file’s contents. However, since your existing file is three characters long, you just write one character at the beginning of the file, leaving the remaining two characters in place.

The easiest fix is to convert nxtDVD to a three character string using something like the following:

set nxtDVD to ((DVDNumber) + 1)

set nxtDVD to padNumber (nxtDVD, 3)

on padNumber (theNumber, minChars)
   set theString to theNumber as string
   repeat until (length of theString >= minChars)
      set theString to "0" & theString
   end repeat
   return theString
end padNumber

This example takes an integer variable and the number of characters you want the string to be. It then repeatedly prepends a “0” to the string until you reach (or exceed) the requested string length.

Once you have a string “002”, you will overwrite the existing three characters “001” and solve your problem.

Incidentally, the alternative solution would be to simply store the integer value (e.g. 1, 2, 3, etc.) in the file rather than a three character string (“001”, “002”, “003”), but either way works.