How to use sf.file to get list of files in a known Directory
Hi there, just recently stumbled on the code sf.file. Have looked at the list of possible functions but not sure how to use sf.file correctly.
I'm looking to read the contents of a folder on my computer and add the file names to a list.
Are either of these the correct starting point?
sf.file.directoryGetEntries():
sf.file.directoryGetFiles();
Any light you can shed @chrscheuer would be amazing!
Many thanks,
Iain
- Christian Scheuer @chrscheuer2021-09-29 16:58:24.990Z
directoryGetEntries
will get you both files and directories in thepath
you're looking under.directoryGetFiles
will only get you files.Example use case:
let textFilePaths = sf.file.directoryGetFiles({ path: `~/Desktop`, searchPattern: '*.txt', }).paths; for(let path of Array.from(textFilePaths)) { log(`Processing file "${path}"...`); } log('Done');
Christian Scheuer @chrscheuer2021-09-29 16:58:50.290Z
Set the
isRecursive
property totrue
to search through all child folders as welllet textFilePaths = sf.file.directoryGetFiles({ path: `~/Desktop`, searchPattern: '*.txt', isRecursive: true, }).paths; for (let path of Array.from(textFilePaths)) { log(`Processing file "${path}"...`); } log('Done');
Christian Scheuer @chrscheuer2021-09-29 17:00:35.628Z
Another example – getting the newest file in a folder:
let newestPathOnDesktop = sf.file.directoryGetFiles({ path: `~/Desktop`, searchPattern: '*.txt', sortOrder: 'LastWriteTimeDesc', }).paths[0]; log(newestPathOnDesktop);
- AAlex Oldroyd @Alex_Oldroyd8
hi christian. When i run this script, it just logs 'Done'. I tried adding
log(textFilePaths)
but this doesn't seem to work either
Christian Scheuer @chrscheuer2023-10-23 00:59:49.670Z
Hi Alex
That script looks for txt files on your Desktop. If you need help with a script doing something else, please use Script Help so we have a full view of what you're trying to do.
- In reply toIain_Anderson⬆:Randy Brown @Randy_Brown
Hi guys! Any way to amend that function to take in the “selected” files on the finder? I’d like to generate an array of these file names.
Thanks!
RandyChristian Scheuer @chrscheuer2024-12-09 16:17:18.604Z
Yes, you can do that like so:
var selectedFilePaths = Array.from(sf.ui.finder.selectedPaths); for(let filePath of selectedFilePaths) { log(filePath); //Do something with this file here... }