If filename/folder exists problem

Hello there,

I’m searching for a simple peace of code which can see if a filename or folder exists and if yes, place a number after the filename/folder. The same thing as OSX finder does when duplicating a folder or file.

Below the script which is for automated CD/DVD exporting to a different location.
I have 300 DVD’s to harddisk to copy. The script is almost perfect but not the aspect of duplicate names.

Two things to make this script better:

  • when a name exist, place a number after it
  • when a DVD has a scratch or defect, beep

Who can help, i think it’s a wonderful script to expand.

Peter Tollenaar

on run
	tell application "Finder"
		set volumesList to list disks
		set oldDesktop to volumesList as text
		repeat
			set volumesList to list disks
			set newDesktop to volumesList as text
			if newDesktop is not oldDesktop then
				repeat with idx from 1 to the number of items of volumesList
					if not (oldDesktop contains item idx of volumesList) then
						set CDName to item idx of volumesList
						set CDRomAlias to CDName as alias
						with timeout of 3600 seconds
							try
								duplicate CDRomAlias to "Backup:"
							on error errorMsg number errorNum
								beep
								display dialog (errorNum as text) & return & errorMsg buttons "OK"
							end try
							eject CDName
						end timeout
					end if
				end repeat
			end if
			set oldDesktop to newDesktop
			delay 5
		end repeat
	end tell
end run

Model: MacBook Pro
AppleScript: 2.1.2
Browser: Safari 534.50
Operating System: Mac OS X (10.6)

For the most efficient way of doing this you should work like a exitence check

  • list the names of the file in the folder file
  • repeat with the name until it doesn’t exists

The reason is that the folder itself has to be opened once.

createNextFileName("testfolder", path to desktop folder as string)

on createNextFileName(baseName, inDirectory)
	tell application "System Events" to set theFiles to name of (every disk item in folder inDirectory whose visible is true)
	if baseName is in theFiles then
		set x to 1
		repeat
			if (baseName & space & x as string) is not in theFiles then
				return baseName & space & x as string
			end if
			set x to x + 1
		end repeat
	end if
	
	return baseName
end createNextFileName