get the name of the parent folder

hi
i actually make a applescript for a futur quicktime droplet.
when i have to save the file, i want the script give the name of the droped file’s parent folder

i’ve try it

set nameSequence to container of myfiles & ".mov"

but that don’t work how i can do for get the parent folder name please ?
thanks

Model: MBP
AppleScript: 2.2.1
Browser: Safari 533.4
Operating System: Mac OS X (10.5)

2 ways: an easy one, and a more difficult one.

easy:

tell application "Finder" to get name of container of (choose file)

[b]harder, but without Finder’s help:[\b]

set myFile to choose file
set cont to stringByDeletingLastPathComponent(POSIX path of myFile)
set cont to lastPathComponent(cont)

(* ===== HANDLERS ===== *)
on stringByDeletingLastPathComponent(filename)
	-- if slash
	if filename is "/" then return filename
	
	-- if ends with slash
	if filename ends with "/" then set filename to (characters 1 thru -2 of filename) as string
	set tid to AppleScript's text item delimiters
	set AppleScript's text item delimiters to "/"
	set allComponents to every text item of filename
	set AppleScript's text item delimiters to ""
	
	-- if no dir
	if (count allComponents) is 1 then return ""
	
	set allComponents to (items 1 thru -2) of allComponents
	
	set AppleScript's text item delimiters to "/"
	set newPath to allComponents as text
	set AppleScript's text item delimiters to ""
	if newPath does not end with "/" then set newPath to (newPath & "/") as string
	
	set AppleScript's text item delimiters to tid
	
	return newPath
end stringByDeletingLastPathComponent

on pathComponents(filename)
	if filename is "" then return {}
	set tid to AppleScript's text item delimiters
	set AppleScript's text item delimiters to "/"
	set components to every text item of filename
	set AppleScript's text item delimiters to ""
	if filename starts with "/" then set item 1 of components to "/"
	
	-- if end with slash
	if item -1 of components is "" then set components to (items 1 thru -2 of components)
	
	set AppleScript's text item delimiters to tid
	return components
end pathComponents

on lastPathComponent(filename)
	set allComponents to my pathComponents(filename)
	if allComponents is {} then return ""
	return item -1 of allComponents
end lastPathComponent

Hope it helps,
ief2

there is another way without the Finder


set parentDirectory to POSIX file (do shell script "dirname " & quoted form of POSIX path of (choose file)) as alias


Hello.

I use this, you should really use a file name as text, but it handles and alias as well. What they don’t handle are posix filenames. In such a case you would really pass with the item delimiter, and specify the correct one,
or coerce :slight_smile: on the outside.



set parentFolderName to baseName(getPathToParentFolder(hfsFileOrFolderPathAsText))

on getPathToParentFolder(hfsFileOrFolderPathAsText)
	-- whether it is a file, a folder,application or bundle.
	local tids, theFile, lastItem
	set hfsFileOrFolderPathAsText to "" & hfsFileOrFolderPathAsText -- doesn't harm.
	set lastItem to -2
	if hfsFileOrFolderPathAsText ends with ":" then set lastItem to -3
	-- we gain an extra text item  the empty one created at the end.
	set {tids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, ":"}
	set hfsFileOrFolderPathAsText to text items 1 thru lastItem of hfsFileOrFolderPathAsText
	set hfsFileOrFolderPathAsText to "" & hfsFileOrFolderPathAsText -- necessary here.
	set AppleScript's text item delimiters to tids
	return hfsFileOrFolderPathAsText
end getPathToParentFolder


on baseName(hfsFileOrFolderPathAsText)
	-- whether it is a file, a folder,application or bundle.
	local tids, theFile, lastItem
	set hfsFileOrFolderPathAsText to "" & hfsFileOrFolderPathAsText -- doesn't harm.
	set lastItem to -1
	if hfsFileOrFolderPathAsText ends with ":" then set lastItem to -2
	set {TID, text item delimiters} to {text item delimiters, ":"}
	set fileName to text item lastItem of (hfsFileOrFolderPathAsText as text)
	set text item delimiters to TID
	return fileName
end baseName



thanks to everyone for your fast answer !

best regards

ok i’ve try all sollution but i have always a problem.
i’m in a droplet so i replace the choose file by the file variable but that don’t work…

on run
	set myfiles to choose file with prompt "Please choose an image from the image sequence:" without showing package contents and invisibles
	open {result}
end run
on open myfiles
	tell application "Finder"
		set foldername to name of {myfiles}
		display dialog "\"" & (foldername as text) & "\""
		set theSequence to POSIX file (do shell script "dirname " & quoted form of POSIX path of myfiles) as alias
		display dialog "\"" & (theSequence as text) & "\""
	end tell
end open

regards

Hello.

Take a look here I have written a couple of handlers, that takes any thing that can go for a file or folder as input. Let me know if they doesn’t work for you. Please.

Edit:

I’m not sure what you really intend to do with your code, but the on open handler takes a list of aliases as input
I have rewritten your code slightly in order to reflect that.


on run
	set myfiles to choose file with prompt "Please choose an image from the image sequence:" without showing package contents and invisibles
	open {result}
end run
on open myfiles
	repeat with afile in myfiles
		tell application "Finder"
			set folderName to my getPathToParentFolderOfAnythingAsText(afile)
			display dialog "\"" & (folderName) & "\""
			--			set theSequence to POSIX file (do shell script "dirname " & quoted form of POSIX path of afile) as alias
			set theSequence to my itemNameOfAnythingAsText(afile)
			--			display dialog "\"" & (theSequence as text) & "\""
			display dialog "\"" & (theSequence) & "\""
		end tell
	end repeat
end open


- © McUsr 2010 and put in Public Domain see: macscripter.net/viewtopic.php?pid=131797#p131797 for reference and terms of use.

on getPathToParentFolderOfAnythingAsText(fileOrFolderPath)
	-- whether it is a file, a folder,application or bundle.
	local tids, theFile, lastItem, tidsToUse
	set tidsToUse to ":"
	try
		(get class of fileOrFolderPath)
	on error number -1728 -- it was a filereference
		set fileOrFolderPath to fileOrFolderPath as alias
	end try
	set fileOrFolderPath to "" & fileOrFolderPath -- doesn't harm.
	if fileOrFolderPath starts with "/" then set tidsToUse to "/"
	
	set lastItem to -2
	if fileOrFolderPath ends with ":" then set lastItem to -3
	-- we gain an extra text item  the empty one created at the end.
	set {tids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, tidsToUse}
	set fileOrFolderPath to text items 1 thru lastItem of fileOrFolderPath
	set fileOrFolderPath to "" & fileOrFolderPath -- necessary here.
	set AppleScript's text item delimiters to tids
	return fileOrFolderPath
end getPathToParentFolderOfAnythingAsText

on itemNameOfAnythingAsText(fileOrFolderPath)
	-- whether it is a file, a folder,application or bundle.
	local tids, theFile, lastItem, tidsToUse
	set tidsToUse to ":"
	try
		(get class of fileOrFolderPath)
	on error number -1728 -- it was a filereference
		set fileOrFolderPath to fileOrFolderPath as alias
	end try
	set fileOrFolderPath to "" & fileOrFolderPath -- doesn't harm.
	if fileOrFolderPath starts with "/" then set tidsToUse to "/"
	set lastItem to -1
	if fileOrFolderPath ends with ":" then set lastItem to -2
	set {tids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, tidsToUse}
	set fileName to text item lastItem of (fileOrFolderPath as text)
	set AppleScript's text item delimiters to tids
	return fileName
end itemNameOfAnythingAsText


All of that seems a bit complicated.

Since the first day I used macOs X, I use this simple handler :


set le_chemin to "Macintosh HD Maxtor:Users:yvan_koenig:Desktop:AppleMods Loader Tutorial.pages:"
set conteneur_1 to my extrait_conteneur(le_chemin)

tell application "Finder" to set une_reference to a reference to item le_chemin
set conteneur_2 to my extrait_conteneur(une_reference)

set un_chemin_Unix to POSIX path of le_chemin
set conteneur_3 to my extrait_conteneur(un_chemin_Unix)

{conteneur_1, conteneur_2, conteneur_3}

--=====

on extrait_conteneur(un_objet)
	tell application "System Events"
		return path of container of disk item (path of disk item (un_objet as text))
	end tell
end extrait_conteneur

Yvan KOENIG (VALLAURIS, France) mercredi 11 août 2010 12:23:08

Hello Yvan.

You are quite right, your solution is simpler. -My handlers are meant to take everything at all times, now they also take quoted Posix paths. You can use them without any regards to what you are passing them, from quoted posix path to a file reference. So they should work in any context, and there is only one name to remember for that functionality!

(The version that handles quoted Posix paths is inCode Exchange)

It may not be the speediest, nor shortest solution, but they will do the job.

Hello again Yvan.

I have now updated the handlers by your help, and they live in code exchange as referred to in the post above.
I just post them here, since I think you will show your solution.

The handlers now handles quotes within quoted Posix paths! And that is thanks to Yvan Koenig! I had never figured out the sequences of characters to make the adjustments to the filenames, which the quoted form does when there are single quotes within, without his code to look at.
I did a waist amount of trial and error before I looked at his code, so I’m not exaggerating anything. :slight_smile:


- © McUsr 2010 and put in Public Domain see: macscripter.net/viewtopic.php?pid=131797#p131797 for reference and terms of use.
on getPathToParentFolderOfAnythingAsText(fileOrFolderPath)
	-- whether it is a file, a folder,application or bundle.
	local tids, theFile, lastItem, tidsToUse, singleQuoteCheck
	set singleQuoteCheck to false
	try
		(get class of fileOrFolderPath)
	on error number -1728 -- it was a filereference
		set fileOrFolderPath to fileOrFolderPath as alias
	end try
	set fileOrFolderPath to "" & fileOrFolderPath -- doesn't harm.
	if fileOrFolderPath starts with "'" and fileOrFolderPath ends with "'" then
		set fileOrFolderPath to text 2 thru -2 of fileOrFolderPath
		set singleQuoteCheck to true
	end if
	set tidsToUse to ":"
	if fileOrFolderPath starts with "/" then set tidsToUse to "/"
	set lastItem to -2
	if fileOrFolderPath ends with ":" then set lastItem to -3
	-- we gain an extra text item  the empty one created at the end.
	set {tids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, tidsToUse}
	set fileOrFolderPath to text items 1 thru lastItem of fileOrFolderPath
	set fileOrFolderPath to "" & fileOrFolderPath
	if singleQuoteCheck is true then
		set AppleScript's text item delimiters to "'\\''"
		set fileOrFolderPath to text items of fileOrFolderPath
		set AppleScript's text item delimiters to "'"
	end if
	-- set AppleScript's text item delimiters to tidsToUse
	set fileOrFolderPath to "" & fileOrFolderPath -- necessary here.
	set AppleScript's text item delimiters to tids
	return fileOrFolderPath
end getPathToParentFolderOfAnythingAsText


on itemNameOfAnythingAsText(fileOrFolderPath)
	-- whether it is a file, a folder,application or bundle.
	local tids, theFile, lastItem, tidsToUse, singleQuoteCheck -- Thanks to Yvan Koenig :)
	set singleQuoteCheck to false
	set tidsToUse to ":"
	try
		(get class of fileOrFolderPath)
	on error number -1728 -- it was a filereference
		set fileOrFolderPath to fileOrFolderPath as alias
	end try
	
	set fileOrFolderPath to "" & fileOrFolderPath -- doesn't harm.
	if fileOrFolderPath starts with "'" and fileOrFolderPath ends with "'" then
		set fileOrFolderPath to text 2 thru -2 of fileOrFolderPath
		set singleQuoteCheck to true
	end if
	if fileOrFolderPath starts with "/" then set tidsToUse to "/"
	set lastItem to -1
	if fileOrFolderPath ends with ":" then set lastItem to -2
	set {tids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, tidsToUse}
	set fileName to text item lastItem of (fileOrFolderPath as text)
	if singleQuoteCheck is true then
		set AppleScript's text item delimiters to "'\\''"
		set fileName to text items of fileName -- as list
		set AppleScript's text item delimiters to "'"
	end if
	set fileName to "" & fileName
	set AppleScript's text item delimiters to tids
	return fileName
end itemNameOfAnythingAsText

Hello.

I have updated the getPathToParentFolderOfAnythingAsText() handler to correctly retain the single quotes after “unquoting” the filename.

Yvan
ta technique marche bien si on precise le chemin dans le script mais ca ne fonctionne pas avec le choose file, et c’est la tout le probleme… je n’arrive pas a le faire marcher avec un resultat de choose file

Yvan’s technic work but not with the choose file method, and that exactly what i try do to

Of course it does work


set theParentPath to extrait_conteneur(choose file)
display dialog theParentPath
--=====

on extrait_conteneur(un_objet)
	tell application "System Events"
		return path of container of disk item (path of disk item (un_objet as text))
	end tell
end extrait_conteneur


Bizarre, vous avez dit bizarre ?

Here is an enhanced script written to play with mcUsr.



set nom_pour_test to "iWork '09 help on nick's request .txt"
set p2d to path to desktop
set le_chemin to (path to desktop as text) & nom_pour_test

tell application "System Events"
	if not (exists file le_chemin) then make new file at end of p2d with properties {name:nom_pour_test}
end tell

set conteneur_1 to my extrait_conteneur(le_chemin)
set nom_1 to my extrait_nom(le_chemin)

tell application "Finder" to set une_reference to a reference to item le_chemin
set conteneur_2 to my extrait_conteneur(une_reference)
set nom_2 to my extrait_nom(une_reference)

set un_chemin_Unix to POSIX path of le_chemin
set conteneur_3 to my extrait_conteneur(un_chemin_Unix)
set nom_3 to my extrait_nom(un_chemin_Unix)

set un_chemin_Unix_quoted to quoted form of POSIX path of le_chemin

set conteneur_4 to my extrait_conteneur(un_chemin_Unix_quoted)
set nom_4 to my extrait_nom(un_chemin_Unix_quoted)

set un_fichier_choisi to (choose file) (* special guest for menthorskillz *)
set conteneur_5 to my extrait_conteneur(un_fichier_choisi)
set nom_5 to my extrait_nom(un_fichier_choisi)

(*
{nom_1, tab, conteneur_1, return, nom_2, tab, conteneur_2, return, nom_3, tab, conteneur_3, return, nom_4, tab, conteneur_4, return, nom_5, tab, conteneur_5}
*)
--=====

on extrait_conteneur(un_objet)
	log un_objet
	set un_objet to un_objet as text
	if (un_objet starts with "'") and (un_objet ends with "'") then
		set un_objet to text 2 thru -2 of my remplace(un_objet, "'\\''", "'")
	end if
	log un_objet
	tell application "System Events"
		return path of container of disk item (path of disk item un_objet)
	end tell
	
end extrait_conteneur

--=====

on extrait_nom(un_objet)
	
	set un_objet to un_objet as text
	if (un_objet starts with "'") and (un_objet ends with "'") then
		set un_objet to text 2 thru -2 of my remplace(un_objet, "'\\''", "'")
	end if
	
	tell application "System Events"
		return name of disk item (path of disk item un_objet)
	end tell
	
end extrait_nom

--=====
(*
replace every occurences of d1 by d2  in text t
*)
on remplace(t, d1, d2)
	local oTIDs, l
	set oTIDs to AppleScript's text item delimiters
	set AppleScript's text item delimiters to d1
	set l to text items of t
	set AppleScript's text item delimiters to d2
	set t to l as text
	set AppleScript's text item delimiters to oTIDs
	return t
end remplace

--=====

If I forgot nothing, it treats every cases.

In all cases, the returned paths are HFS ones.

Yvan KOENIG (VALLAURIS, France) mercredi 11 août 2010 18:39:07

Hello Yvan.

I find your solution to be maybe better and maybe more efficient (System Events).
If I compare mine and yours solution against your solution, then I’d say I prefer yours and mine.

Because here you don’t have to do any preparations, it just handles everything. And I didn’t start off writing those handlers with you in mind, more so with me in mind! :slight_smile: -I like to have it practical, something that works in any situation. I’m especially pleased with the way it handles single quotes. :slight_smile: When such stuff turns up, it tend to be time consuming. Well, my and your solution breaks if you send it a reference to something that is not a file, but then you are really asking for it, and in my opinion “has it coming” anyway! :smiley:

Thanks and thanks again for your help and collaboration! :slight_smile: -I had never managed this without you.

Your singlehanded solution does exactly the same, but you have to do more up front. Then again, as we speak mine and yours solution, doesn’t handle non existing files very well, (intentionally by me).

I don’t have to ask Stefan which solution he would prefer either, but Stefan isn’t exactly any newbie to scripting. :slight_smile:

All in all, I’m pretty damn sure that mine and yours solution Yvan, can save a fair amount of time to people who aren’t totally comfortable with aliases and unicode texts and file references and such, not to mention Posix paths, but just want the job to be done.

I know this is an old thread (2010), but I just ran across this very cool trick I wanted to share with all. This is the simplest method of getting the parent folder path I have seen:


set fileAlias to path to me
set pathParentPOSIX to POSIX path of ((fileAlias as text) & "::")
set pathParentHFS to POSIX file pathParentPOSIX as text

--- Of course, if all you need is the HFS path ---
set pathParentHFS to POSIX file (POSIX path of ((fileAlias as text) & "::")) as text


BASED ON:

Thank you for this tip.
I would be glad to get an explanation upon the mechanism at work in this operation.

Yvan KOENIG running Sierra 10.12.6 in French (VALLAURIS, France) vendredi 21 juillet 2017 11:37:23

You don’t need the POSIX path if you only want an HFS result:

set filePath to (path to me as text)
set parentPathHFS to (filePath & "::") as alias as text

Hello Nigel

Do you know the mechanism at work in this interesting tip ?

Yvan KOENIG running Sierra 10.12.6 in French (VALLAURIS, France) vendredi 21 juillet 2017 12:14:10

Hi Yvan.

I’m afraid I don’t. It seems to be the vestige of some relative path method built into HFS+ which has never become official usage — not in AppleScript, anyway.

(path to desktop as text) & "::Library:"
result as alias

Nowadays, a colon at the beginning of an HFS path has an effect similar to the slash at the beginning of a POSIX path — probably for POSIX compatibility:

":" as alias

This now returns an alias to the startup disk. But in days of yore, before Mac OS X came along, it was a popular method for returning an alias to the container of the application running the script. The more colons you used, the further up the folder hierarchy you went.

It’s probably not a good idea to use multi-colon hacks. Fun though. :wink:

Addendum: In Mac OS 8.6, with AppleScript’s TIDs set at their default value, it was possible to get the container of the application running a script with this:

tell AppleScript's text item delimiters to its middle Wednesday as alias

Owing to a bug at the time, {“”}'s middle Wednesday returned the “” instead of erroring. And “” as alias had the same effect as “:” as alias. :slight_smile: