Save Folder Hierarchy as TXT file

This site has an identical script written by Nigel Garvey.

It works great, but I would like the script to return only the contents of folders without affecting packages. Therefore, I wrote for myself (and for other users) my own version that does not use the find utility:


property file_id : null

set rootFolder to choose folder with prompt "Choose the root folder"
set logFileHfsPath to (path to desktop as string) & "Folder Hierarchy.txt"

try
	set file_id to open for access file logFileHfsPath with write permission
on error
	close access file logFileHfsPath
	set file_id to open for access file logFileHfsPath with write permission
end try

set eof of file_id to 0
write ("Contents of " & rootFolder & return & return) to file_id
write ("Start " & (current date) & return) to file_id -- starting at eof
my do_subfolders(rootFolder, "")
write (return & return) to file_id starting at eof
close access file_id
display notification "Folder hierarchy TXT" & linefeed & "created on the desktop." with title "Folder hierarchy.script"

on do_subfolders(this_folder, name_prefix)
	tell application "Finder"
		write (return & name_prefix & (name of this_folder)) as «class utf8» to file_id -- starting at eof
		set file_list to files of this_folder
		repeat with this_file in file_list
			write (return & name_prefix & tab & (name of this_file)) as «class utf8» to file_id -- starting at eof
		end repeat
		set folder_list to folders of this_folder
		repeat with this_subfolder in folder_list
			my do_subfolders(this_subfolder, tab & name_prefix)
		end repeat
	end tell
end do_subfolders
1 Like

An interesting analogue of the tree utility, but here’s what I noticed.
If the file name contains Cyrillic, Chinese characters or letters of the Korean alphabet, the resulting file contains mojibakes.

Example:
Contents of Macintosh HD:Users:vyakob:Temp:Test:

Start среда, 7 июня 2023 г. в 21:41:55

Test
ASTRA.txt
–°–љ–Є–Љ–Њ–Ї —Н–Ї—А–∞–љ–∞ 2023-05-04 –≤ 15.45.27.png
–°–љ–Є–Љ–Њ–Ї.PNG
–≠–Ї—Б–њ–Њ—А—В –і–Њ–Ї—Г–Љ–µ–љ—В–Њ–≤ –≤ —Д–Њ—А–Љ–∞—В MS.pages
бДТбЕ°бЖЂбДАбЕ≥бЖѓбДВбЕ°бЖѓ.txt
дЄ≠жЦЗ.txt

If you remove “«class utf8»” in the code, the Cyrillic alphabet in the document is displayed normally, but there are no Chinese and Korean characters.

Contents of Macintosh HD:Users:vyakob:Temp:Test:

Start среда, 7 июня 2023 г. в 21:50:52

Test
ASTRA.txt
Снимок экрана 2023-05-04 в 15.45.27.png
Снимок.PNG
Экспорт документов в формат MS.pages
???.txt
??.txt

In theory, UTF8 is universal, and should work with it normally, but something is going wrong.

screen

It worked fine for me (taken directly from @KniazidisR’s post).

When opening the resulting text file, I used textedit, first with automatic encoding detection and then set to use UTF-8 and in both instances, it appeared the same.

My default language is English-Canadian, if that makes any difference.