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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |