Skip to content

fs_utils

Filesystem and file-path utilities.

This module collects general purpose filesystem helpers: path manipulation and normalization, file checks and copies, atomic file writes, content read/write (read_content/write_content), temporary (unique) paths, directory size computation and file search over a list of folders.

home()

Returns the user home directory path.

Source code in py_misc_utils/fs_utils.py
23
24
25
def home():
  """Returns the user home directory path."""
  return pathlib.Path.home()

maybe_remove(path)

Removes a file, if it exists.

Parameters:

Name Type Description Default
path

The file path to remove.

required
Source code in py_misc_utils/fs_utils.py
28
29
30
31
32
33
34
35
def maybe_remove(path):
  """Removes a file, if it exists.

  Args:
    path: The file path to remove.
  """
  if os.path.exists(path):
    os.remove(path)

is_binary(fd)

Checks whether a file object is opened in binary mode.

Parameters:

Name Type Description Default
fd

The file object to check.

required

Returns:

Type Description

True if the file object is opened in binary mode - either per its

'b' mode flag, or because it does not implement the text I/O

interface.

Source code in py_misc_utils/fs_utils.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def is_binary(fd):
  """Checks whether a file object is opened in binary mode.

  Args:
    fd: The file object to check.

  Returns:
    True if the file object is opened in binary mode - either per its
    'b' mode flag, or because it does not implement the text I/O
    interface.
  """
  if (mode := getattr(fd, 'mode', None)) is not None:
    return 'b' in mode

  return not isinstance(fd, io.TextIOBase)

link_or_copy(src_path, dest_path)

Links a file, falling back to symlinking and then copying.

Creates dest_path as a hard link of src_path if possible; if the hard link cannot be created - e.g. because the paths are on different filesystems - a symbolic link is used; if also the symlink cannot be created - e.g. on filesystems not supporting them - the file is copied.

Parameters:

Name Type Description Default
src_path

The source file path.

required
dest_path

The destination file path.

required

Returns:

Type Description

The destination file path.

Source code in py_misc_utils/fs_utils.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def link_or_copy(src_path, dest_path):
  """Links a file, falling back to symlinking and then copying.

  Creates dest_path as a hard link of src_path if possible; if the
  hard link cannot be created - e.g. because the paths are on different
  filesystems - a symbolic link is used; if also the symlink cannot be
  created - e.g. on filesystems not supporting them - the file is
  copied.

  Args:
    src_path: The source file path.
    dest_path: The destination file path.

  Returns:
    The destination file path.
  """
  try:
    os.link(src_path, dest_path)

    return dest_path
  except OSError as ex:
    alog.debug(f'Harklink failed from "{src_path}" to "{dest_path}", trying symlink. ' \
               f'Error was: {ex}')

  try:
    os.symlink(src_path, dest_path)

    return dest_path
  except OSError as ex:
    alog.debug(f'Symlink failed from "{src_path}" to "{dest_path}", going to copy. ' \
               f'Error was: {ex}')

  shutil.copyfile(src_path, dest_path)
  shutil.copystat(src_path, dest_path)

  return dest_path

is_newer_file(path, other)

Checks whether a file is newer than another one.

Parameters:

Name Type Description Default
path

The file path to check.

required
other

The reference file path.

required

Returns:

Type Description

True if the modification time of path is newer than the one of

other.

Source code in py_misc_utils/fs_utils.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def is_newer_file(path, other):
  """Checks whether a file is newer than another one.

  Args:
    path: The file path to check.
    other: The reference file path.

  Returns:
    True if the modification time of path is newer than the one of
    other.
  """
  return os.stat(path).st_mtime > os.stat(other).st_mtime

os_opener(*args, **kwargs)

Builds an opener function for os.open()-like APIs.

Parameters:

Name Type Description Default
*args

Positional arguments passed to os.open().

()
**kwargs

Keyword arguments passed to os.open().

{}

Returns:

Type Description

A callable opening a file descriptor with the given arguments.

Source code in py_misc_utils/fs_utils.py
107
108
109
110
111
112
113
114
115
116
117
def os_opener(*args, **kwargs):
  """Builds an opener function for os.open()-like APIs.

  Args:
    *args: Positional arguments passed to os.open().
    **kwargs: Keyword arguments passed to os.open().

  Returns:
    A callable opening a file descriptor with the given arguments.
  """
  return functools.partial(os.open, *args, **kwargs)

safe_rmtree(path, **kwargs)

Removes a directory tree in an atomic fashion.

The directory is first renamed to a temporary path - so that other threads/processes will not see a partially-deleted tree - and then removed.

Parameters:

Name Type Description Default
path

The directory tree to remove.

required
**kwargs

Keyword arguments passed to shutil.rmtree() - like ignore_errors.

{}

Raises:

Type Description
FileNotFoundError

If the directory does not exist and ignore_errors is not set.

Source code in py_misc_utils/fs_utils.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def safe_rmtree(path, **kwargs):
  """Removes a directory tree in an atomic fashion.

  The directory is first renamed to a temporary path - so that other
  threads/processes will not see a partially-deleted tree - and then
  removed.

  Args:
    path: The directory tree to remove.
    **kwargs: Keyword arguments passed to shutil.rmtree() - like
      ignore_errors.

  Raises:
    FileNotFoundError: If the directory does not exist and
      ignore_errors is not set.
  """
  tpath = temp_path(nspath=path)
  try:
    os.rename(path, tpath)
  except FileNotFoundError:
    if not kwargs.get('ignore_errors', False):
      raise
  else:
    shutil.rmtree(tpath, **kwargs)

readall(fd)

Reads the whole content of a file.

Parameters:

Name Type Description Default
fd

The file to read: either a path, or a file descriptor - as returned by os.open(), not a buffered file object.

required

Returns:

Type Description

The whole file content, as bytes.

Example
import os
import tempfile

from py_misc_utils import fs_utils as fsu

path = os.path.join(tempfile.mkdtemp(), 'data.bin')
with open(path, 'wb') as fd:
  fd.write(b'content')

fd = os.open(path, os.O_RDONLY)
data = fsu.readall(fd)
os.close(fd)
print(data)
Source code in py_misc_utils/fs_utils.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def readall(fd):
  """Reads the whole content of a file.

  Args:
    fd: The file to read: either a path, or a file descriptor - as
      returned by os.open(), not a buffered file object.

  Returns:
    The whole file content, as bytes.

  Example:
    import os
    import tempfile

    from py_misc_utils import fs_utils as fsu

    path = os.path.join(tempfile.mkdtemp(), 'data.bin')
    with open(path, 'wb') as fd:
      fd.write(b'content')

    fd = os.open(path, os.O_RDONLY)
    data = fsu.readall(fd)
    os.close(fd)
    print(data)
  """
  if isinstance(fd, str):
    with osfd.OsFd(fd, os.O_RDONLY) as ifd:
      return readall(ifd)
  else:
    sres = os.stat(fd)
    os.lseek(fd, 0, os.SEEK_SET)

    return os.read(fd, sres.st_size)

read_content(path, binary=True)

Reads the whole content of a file.

Parameters:

Name Type Description Default
path

The file path to read (string).

required
binary

If True (default), returns the raw bytes content. Otherwise returns the content decoded as UTF-8 str.

True

Returns:

Type Description

The whole file content, as bytes if binary=True, else as str.

Example
import os
import tempfile

from py_misc_utils import fs_utils as fsu

root = tempfile.mkdtemp()
path = os.path.join(root, 'notes.txt')
with open(path, 'w') as fd:
  fd.write('hello')

print(fsu.read_content(path, binary=False))  # hello
print(fsu.read_content(path))  # b'hello'
Source code in py_misc_utils/fs_utils.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def read_content(path, binary=True):
  """Reads the whole content of a file.

  Args:
    path: The file path to read (string).
    binary: If True (default), returns the raw bytes content.
      Otherwise returns the content decoded as UTF-8 str.

  Returns:
    The whole file content, as bytes if binary=True, else as str.

  Example:
    import os
    import tempfile

    from py_misc_utils import fs_utils as fsu

    root = tempfile.mkdtemp()
    path = os.path.join(root, 'notes.txt')
    with open(path, 'w') as fd:
      fd.write('hello')

    print(fsu.read_content(path, binary=False))  # hello
    print(fsu.read_content(path))  # b'hello'
  """
  if binary:
    with open(path, 'rb') as f:
      return f.read()
  else:
    with open(path, 'r', encoding='utf-8') as f:
      return f.read()

write_content(path, data, binary=True)

Writes data to a file.

Parameters:

Name Type Description Default
path

The file path to write to (string).

required
data

The data to write. If binary=True, data is written as bytes (a str argument is encoded as UTF-8). If binary=False, data is written as str (a bytes argument is decoded as UTF-8).

required
binary

If True (default), writes bytes; otherwise writes str.

True
Source code in py_misc_utils/fs_utils.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def write_content(path, data, binary=True):
  """Writes data to a file.

  Args:
    path: The file path to write to (string).
    data: The data to write. If binary=True, data is written as bytes
      (a str argument is encoded as UTF-8). If binary=False, data is
      written as str (a bytes argument is decoded as UTF-8).
    binary: If True (default), writes bytes; otherwise writes str.
  """
  if binary:
    if isinstance(data, str):
      data = data.encode('utf-8')
    with open(path, 'wb') as f:
      f.write(data)
  else:
    if isinstance(data, bytes):
      data = data.decode('utf-8')
    with open(path, 'w', encoding='utf-8') as f:
      f.write(data)

stat(path)

Stats a file, returning None instead of raising on failure.

Parameters:

Name Type Description Default
path

The file path to stat.

required

Returns:

Type Description

The file stat result, or None if the file does not exist - or cannot

be accessed.

Source code in py_misc_utils/fs_utils.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def stat(path):
  """Stats a file, returning None instead of raising on failure.

  Args:
    path: The file path to stat.

  Returns:
    The file stat result, or None if the file does not exist - or cannot
    be accessed.
  """
  try:
    return os.stat(path)
  except OSError:
    pass

path_split(path)

Splits a path into its components.

Parameters:

Name Type Description Default
path

The path to split.

required

Returns:

Type Description

The list of path components - the first one possibly being the root

(drive/volume) component.

Example
from py_misc_utils import fs_utils as fsu

print(fsu.path_split('/a/b/c.txt'))  # ['/', 'a', 'b', 'c.txt']
print(fsu.path_split('a/b/c.txt'))  # ['a', 'b', 'c.txt']
Source code in py_misc_utils/fs_utils.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def path_split(path):
  """Splits a path into its components.

  Args:
    path: The path to split.

  Returns:
    The list of path components - the first one possibly being the root
    (drive/volume) component.

  Example:
    from py_misc_utils import fs_utils as fsu

    print(fsu.path_split('/a/b/c.txt'))  # ['/', 'a', 'b', 'c.txt']
    print(fsu.path_split('a/b/c.txt'))  # ['a', 'b', 'c.txt']
  """
  path_parts = []
  while True:
    parts = os.path.split(path)
    if parts[0] == path:
      path_parts.append(parts[0])
      break
    elif parts[1] == path:
      path_parts.append(parts[1])
      break
    else:
      path = parts[0]
      path_parts.append(parts[1])

  path_parts.reverse()

  return path_parts

drop_ext(path, exts)

Removes the file extension from a path.

Parameters:

Name Type Description Default
path

The file path.

required
exts

The extension - or list/tuple of extensions - to remove, with the leading dot.

required

Returns:

Type Description

The path without the matched extension, or the original path if the

extension is not matched.

Example
from py_misc_utils import fs_utils as fsu

print(fsu.drop_ext('archive.tar.gz', ['.tar', '.gz']))  # archive.tar
print(fsu.drop_ext('file.txt', '.md'))  # file.txt
Source code in py_misc_utils/fs_utils.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
def drop_ext(path, exts):
  """Removes the file extension from a path.

  Args:
    path: The file path.
    exts: The extension - or list/tuple of extensions - to remove, with
      the leading dot.

  Returns:
    The path without the matched extension, or the original path if the
    extension is not matched.

  Example:
    from py_misc_utils import fs_utils as fsu

    print(fsu.drop_ext('archive.tar.gz', ['.tar', '.gz']))  # archive.tar
    print(fsu.drop_ext('file.txt', '.md'))  # file.txt
  """
  xpath, ext = os.path.splitext(path)

  if isinstance(exts, str):
    return xpath if ext == exts else path

  return xpath if ext in exts else path

normpath(path)

Normalizes a path - expanding user/vars and making it absolute.

Parameters:

Name Type Description Default
path

The path to normalize.

required

Returns:

Type Description

The normalized absolute path.

Source code in py_misc_utils/fs_utils.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def normpath(path):
  """Normalizes a path - expanding user/vars and making it absolute.

  Args:
    path: The path to normalize.

  Returns:
    The normalized absolute path.
  """
  path = os.path.expanduser(path)
  path = os.path.expandvars(path)
  path = os.path.abspath(path)

  return os.path.normpath(path)

subst_path(path, ref_path)

Substitutes placeholders of a reference file path into a template.

Parameters:

Name Type Description Default
path

The path template, holding $B, $D, $R, $N and $X placeholders.

required
ref_path

The reference file path, whose components are substituted into the template.

required

Returns:

Type Description

The path with the substituted placeholders - where $B is the

reference file name, $D its directory, $R the whole reference path,

$N the file name without extension and $X the extension.

Example
from py_misc_utils import fs_utils as fsu

ref = '/data/in/file.tar.gz'
print(fsu.subst_path('$B.bak', ref))  # file.tar.gz.bak
print(fsu.subst_path('$D/out.bin', ref))  # /data/in/out.bin
print(fsu.subst_path('$N.txt', ref))  # file.tar.txt
print(fsu.subst_path('prefix$X', ref))  # prefix.gz
Source code in py_misc_utils/fs_utils.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
def subst_path(path, ref_path):
  """Substitutes placeholders of a reference file path into a template.

  Args:
    path: The path template, holding $B, $D, $R, $N and $X placeholders.
    ref_path: The reference file path, whose components are substituted
      into the template.

  Returns:
    The path with the substituted placeholders - where $B is the
    reference file name, $D its directory, $R the whole reference path,
    $N the file name without extension and $X the extension.

  Example:
    from py_misc_utils import fs_utils as fsu

    ref = '/data/in/file.tar.gz'
    print(fsu.subst_path('$B.bak', ref))  # file.tar.gz.bak
    print(fsu.subst_path('$D/out.bin', ref))  # /data/in/out.bin
    print(fsu.subst_path('$N.txt', ref))  # file.tar.txt
    print(fsu.subst_path('prefix$X', ref))  # prefix.gz
  """
  spath = os.path.abspath(ref_path)
  dpath = os.path.dirname(spath)
  fname = os.path.basename(spath)
  name, ext = os.path.splitext(fname)

  path_template = string.Template(path)

  return path_template.substitute(B=fname,
                                  D=dpath,
                                  R=os.path.join(dpath, fname),
                                  N=name,
                                  X=ext)

localfs_mount(path)

Returns the mount point of a local filesystem path.

Parameters:

Name Type Description Default
path

The path whose mount point is looked up.

required

Returns:

Type Description

The closest existing ancestor of the path which is a mount point -

or the filesystem root, if none is found.

Source code in py_misc_utils/fs_utils.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
def localfs_mount(path):
  """Returns the mount point of a local filesystem path.

  Args:
    path: The path whose mount point is looked up.

  Returns:
    The closest existing ancestor of the path which is a mount point -
    or the filesystem root, if none is found.
  """
  while True:
    parent_path = os.path.dirname(path)
    if path == parent_path or os.path.ismount(path):
      return path
    path = parent_path

enum_chunks(stream, chunk_size=16 * 1024 ** 2)

Enumerates the chunks of data of a stream.

Parameters:

Name Type Description Default
stream

The stream to read.

required
chunk_size

The maximum size of each chunk, in bytes.

16 * 1024 ** 2

Yields:

Type Description

Chunks of data, as bytes - the last one possibly being shorter than

the chunk size.

Source code in py_misc_utils/fs_utils.py
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
def enum_chunks(stream, chunk_size=16 * 1024**2):
  """Enumerates the chunks of data of a stream.

  Args:
    stream: The stream to read.
    chunk_size: The maximum size of each chunk, in bytes.

  Yields:
    Chunks of data, as bytes - the last one possibly being shorter than
    the chunk size.
  """
  while True:
    data = stream.read(chunk_size)
    if data:
      yield data
    if chunk_size > len(data):
      break

du(path, follow_symlinks=None, visited=None)

Computes the disk usage of a file or a directory tree.

Parameters:

Name Type Description Default
path

The file or directory tree root path.

required
follow_symlinks

Whether symlinks are followed - in which case linked files/directories are accounted for as well. By default symlinks are not followed.

None
visited

An optional set of already-visited paths, allowing the traversal of multiple trees sharing paths without accounting the shared paths twice.

None

Returns:

Type Description

The total size - in bytes - of the file, or of the files held by the

directory tree.

Raises:

Type Description
FileNotFoundError

If the path does not exist.

Source code in py_misc_utils/fs_utils.py
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
def du(path, follow_symlinks=None, visited=None):
  """Computes the disk usage of a file or a directory tree.

  Args:
    path: The file or directory tree root path.
    follow_symlinks: Whether symlinks are followed - in which case
      linked files/directories are accounted for as well. By default
      symlinks are not followed.
    visited: An optional set of already-visited paths, allowing the
      traversal of multiple trees sharing paths without accounting the
      shared paths twice.

  Returns:
    The total size - in bytes - of the file, or of the files held by the
    directory tree.

  Raises:
    FileNotFoundError: If the path does not exist.
  """
  visited = set() if visited is None else visited
  follow_symlinks = follow_symlinks not in (None, False)
  size, dirs = 0, []
  if path not in visited:
    visited.add(path)
    if os.path.isdir(path) and (follow_symlinks or not os.path.islink(path)):
      with os.scandir(path) as sdit:
        for de in sdit:
          if de.is_file(follow_symlinks=follow_symlinks):
            sres = de.stat()
            size += sres.st_size
          elif de.is_dir(follow_symlinks=follow_symlinks):
            dirs.append(de.name)

      for dname in dirs:
        size += du(os.path.join(path, dname),
                   follow_symlinks=follow_symlinks,
                   visited=visited)
    elif follow_symlinks or not os.path.islink(path):
      size += os.path.getsize(path)

  return size

find_path(name, paths, checkfn=os.path.exists)

Searches for a file name in a list of folders.

Parameters:

Name Type Description Default
name

The file name to search.

required
paths

The list of folder paths to search into.

required
checkfn

An optional function checking whether the candidate path exists - os.path.exists by default.

exists

Returns:

Type Description

The first matching path found, or None if no folder holds the file

name.

Source code in py_misc_utils/fs_utils.py
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
def find_path(name, paths, checkfn=os.path.exists):
  """Searches for a file name in a list of folders.

  Args:
    name: The file name to search.
    paths: The list of folder paths to search into.
    checkfn: An optional function checking whether the candidate path
      exists - os.path.exists by default.

  Returns:
    The first matching path found, or None if no folder holds the file
    name.
  """
  for path in paths:
    cpath = os.path.join(path, name)
    if checkfn(cpath):
      return cpath

temp_path(nspath=None, nsdir=None, rndsize=_TMPFN_RNDSIZE)

Builds a unique (temporary) path.

Parameters:

Name Type Description Default
nspath

An optional base path: the unique path is built by inserting a random suffix between its base name and its extension. If None, the path is built inside a namespace directory.

None
nsdir

The directory where the unique path is built - when nspath is None. If None, the system temp directory is used.

None
rndsize

The length of the random suffix.

_TMPFN_RNDSIZE

Returns:

Type Description

A unique path - not clashing with already-existing files.

Source code in py_misc_utils/fs_utils.py
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
def temp_path(nspath=None, nsdir=None, rndsize=_TMPFN_RNDSIZE):
  """Builds a unique (temporary) path.

  Args:
    nspath: An optional base path: the unique path is built by inserting
      a random suffix between its base name and its extension. If None,
      the path is built inside a namespace directory.
    nsdir: The directory where the unique path is built - when nspath is
      None. If None, the system temp directory is used.
    rndsize: The length of the random suffix.

  Returns:
    A unique path - not clashing with already-existing files.
  """
  if nspath is not None:
    bpath, ext = os.path.splitext(nspath)

    return f'{bpath}.{rngu.rand_string(rndsize)}{ext}'

  nsdir = tempfile.gettempdir() if nsdir is None else nsdir

  return os.path.join(nsdir, f'{rngu.rand_string(rndsize)}.tmp')

atomic_write(path, mode='wb', create_parents=False)

Writes a file atomically.

The file is first written into a temporary path, and then atomically renamed over the destination path - so that readers never observe a partially-written file. If the write fails, the destination file is left untouched.

Parameters:

Name Type Description Default
path

The destination file path.

required
mode

The open mode of the temporary file.

'wb'
create_parents

Whether the parent directory of the destination path is created if missing.

False

Yields:

Type Description

The open file object of the temporary file.

Source code in py_misc_utils/fs_utils.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
@contextlib.contextmanager
def atomic_write(path, mode='wb', create_parents=False):
  """Writes a file atomically.

  The file is first written into a temporary path, and then atomically
  renamed over the destination path - so that readers never observe a
  partially-written file. If the write fails, the destination file is
  left untouched.

  Args:
    path: The destination file path.
    mode: The open mode of the temporary file.
    create_parents: Whether the parent directory of the destination
      path is created if missing.

  Yields:
    The open file object of the temporary file.
  """
  tpath = temp_path(nspath=path)

  if create_parents:
    os.makedirs(os.path.dirname(path), exist_ok=True)

  completed = False
  try:
    with open(tpath, mode=mode) as fd:
      yield fd
    completed = True
  finally:
    if completed:
      os.replace(tpath, path)
    else:
      os.remove(tpath)

cwd(path)

Changes the current working directory within a context.

Parameters:

Name Type Description Default
path

The working directory path to switch to.

required

Yields:

Type Description

The new working directory path.

Source code in py_misc_utils/fs_utils.py
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
@contextlib.contextmanager
def cwd(path):
  """Changes the current working directory within a context.

  Args:
    path: The working directory path to switch to.

  Yields:
    The new working directory path.
  """
  cpath = os.getcwd()
  os.chdir(path)
  try:
    yield path
  finally:
    os.chdir(cpath)