The file tree is as follwing:
- foo
- lorem
- ipsum <-
- baz <-
- bar
- baz
The currently visited file is ipsum
. Now I want to find the first
baz
and the directory it is in. How do I walk up the tree from
ipsum
in elisp?
walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). root : Prints out directories only from what you specified.
To traverse the directory in Python, use the os. walk() function. The os. walk() function accepts four arguments and returns 3-tuple, including dirpath, dirnames, and filenames.
topdown − If optional argument topdown is True or not specified, directories are scanned from top-down. If topdown is set to False, directories are scanned from bottom-up. onerror − This can show error to continue with the walk, or raise the exception to abort the walk.
A directory structure/system/tree is simply a layout of directories on your computer.
You want locate-dominating-file
.
(defun parent-directory (dir)
(unless (equal "/" dir)
(file-name-directory (directory-file-name dir))))
(defun find-file-in-heirarchy (current-dir fname)
"Search for a file named FNAME upwards through the directory hierarchy, starting from CURRENT-DIR"
(let ((file (concat current-dir fname))
(parent (parent-directory (expand-file-name current-dir))))
(if (file-exists-p file)
file
(when parent
(find-file-in-heirarchy parent fname)))))
If the result is not nil, you can extract the file's directory using file-name-directory
, like so:
(let ((file (find-file-in-heirarchy (buffer-file-name) "baz")))
(when file
(file-name-directory file)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With