MCPcopy Create free account
hub / github.com/ipython/traitlets / filefind

Function filefind

traitlets/utils/__init__.py:15–68  ·  view source on GitHub ↗

Find a file by looking through a sequence of paths. This iterates through a sequence of paths looking for a file and returns the full, absolute path of the first occurrence of the file. If no set of path dirs is given, the filename is tested as is, after running through :func:`expa

(filename: str, path_dirs: Sequence[str] | None = None)

Source from the content-addressed store, hash-verified

13
14
15def filefind(filename: str, path_dirs: Sequence[str] | None = None) -> str:
16 """Find a file by looking through a sequence of paths.
17
18 This iterates through a sequence of paths looking for a file and returns
19 the full, absolute path of the first occurrence of the file. If no set of
20 path dirs is given, the filename is tested as is, after running through
21 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
22
23 filefind('myfile.txt')
24
25 will find the file in the current working dir, but::
26
27 filefind('~/myfile.txt')
28
29 Will find the file in the users home directory. This function does not
30 automatically try any paths, such as the cwd or the user's home directory.
31
32 Parameters
33 ----------
34 filename : str
35 The filename to look for.
36 path_dirs : str, None or sequence of str
37 The sequence of paths to look for the file in. If None, the filename
38 need to be absolute or be in the cwd. If a string, the string is
39 put into a sequence and the searched. If a sequence, walk through
40 each element and join with ``filename``, calling :func:`expandvars`
41 and :func:`expanduser` before testing for existence.
42
43 Returns
44 -------
45 Raises :exc:`IOError` or returns absolute path to file.
46 """
47
48 # If paths are quoted, abspath gets confused, strip them...
49 filename = filename.strip('"').strip("'")
50 # If the input is an absolute path, just check it exists
51 if os.path.isabs(filename) and os.path.isfile(filename):
52 return filename
53
54 if path_dirs is None:
55 path_dirs = ("",)
56 elif isinstance(path_dirs, str):
57 path_dirs = (path_dirs,)
58 elif isinstance(path_dirs, pathlib.Path):
59 path_dirs = (str(path_dirs),)
60
61 for path in path_dirs:
62 if path == ".":
63 path = os.getcwd()
64 testname = expand_path(os.path.join(path, filename))
65 if os.path.isfile(testname):
66 return os.path.abspath(testname)
67
68 raise OSError(f"File {filename!r} does not exist in any of the search paths: {path_dirs!r}")
69
70
71def expand_path(s: str) -> str:

Callers 1

_find_fileMethod · 0.85

Calls 1

expand_pathFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…