Creating folders from filenames issue when folder already exists

I’ve got a script that will create a folder with the same name as the first 6 characters of the filename and then move the file into the new folder. There are going to be conflicts because there are 4 files in the file list that will match on the first 6 characters.

For example:

123456.tif
123456_cp.jpg
123456_sv.jpg
123456_tm.jpg

234567.tif
234567_cp.jpg
234567_sv.jpg
234567_th.jpg

I want to create a folder named 123456 and then move all 4 of the above files into that new folder. Then do it again for 234567. My if then statement is not working correctly.

tell application "Finder"
	set sourcePath to choose folder with prompt "Please select SOURCE folder:"
	set savePath to choose folder with prompt "Please select DESTINATION folder:"
	set fileList to (files of entire contents of sourcePath) as alias list
end tell


repeat with oneFileName in fileList
	tell application "Finder"
		set Filename to name of contents of oneFileName
		set folderName to text 1 thru 6 of Filename
		if folder (savePath & folderName) exists then
			move file Filename of folder savePath to folder folderName of folder savePath
		else
			make new folder at folder savePath with properties {name:folderName}
			move file Filename of folder savePath to folder folderName of folder savePath
		end if
	end tell
end repeat

same problem as in your Photoshop script:

savePath is an alias and you can’t append text like a file name to an alias.
Second problem is you’re going to move file names (FileName) instead of the file itself (oneFileName), this can’t work either


tell application "Finder"
	set sourcePath to choose folder with prompt "Please select SOURCE folder:"
	set savePath to (choose folder with prompt "Please select DESTINATION folder:") as text
	set fileList to (files of entire contents of sourcePath) as alias list
end tell

repeat with oneFileName in fileList
	tell application "Finder"
		set folderName to text 1 thru 6 of (get name of oneFileName)
		if not (folder (savePath & folderName) exists) then make new folder at folder savePath with properties {name:folderName}
		move oneFileName to folder (savePath & folderName)
	end tell
end repeat

Thank you thank you thank you Stefan!

If there was a point system I’d give you massive points for all your help.