Skip to content

file_fs

File-based FileSystem implementation using the local filesystem.

This module provides FileFs, the default FileSystem backend which operates on plain local paths. Since files are already local, as_local() returns the path unchanged and blocks can be read directly from the file.

Example
import os
import tempfile

from py_misc_utils.fs import file_fs

root = tempfile.mkdtemp()
path = os.path.join(root, 'f.txt')

with open(path, 'w') as fd:
  fd.write('hello')

fs = file_fs.FileFs()

print(fs.stat(path).st_size)

FileReader

Reader producing blocks of data from a local file.

Source code in py_misc_utils/fs/file_fs.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
class FileReader:
  """Reader producing blocks of data from a local file."""

  def __init__(self, path):
    """Initialize the reader.

    Args:
      path: Local path of the file to read.
    """
    # Local path of the file to read.
    self._path = path

  @classmethod
  def tag(cls, sres):
    """Build a cache tag from a stat result.

    Args:
      sres: os.stat_result of the file.

    Returns:
      The cache tag embedding size and modification time.
    """
    return chf.make_tag(size=sres.st_size, mtime=sres.st_mtime)

  def support_blocks(self):
    """Return True since local files support direct block reads."""
    return True

  def read_block(self, bpath, offset, size):
    """Read a block of data from a file.

    Args:
      bpath: Path of the file to read from.
      offset: Offset in the file where reading starts.
      size: Number of bytes to read.

    Returns:
      The requested data as bytes.
    """
    if offset != chf.CachedBlockFile.WHOLE_OFFSET:
      with (osfd.OsFd(self._path, os.O_RDONLY) as
            rfd, osfd.OsFd(bpath, os.O_CREAT | os.O_TRUNC | os.O_WRONLY,
                           mode=0o440) as wfd):
        if os.lseek(rfd, offset, os.SEEK_SET) != offset:
          alog.xraise(RuntimeError, f'Unable to seek {self._path} at offset {offset}')
        data = os.read(rfd, size)
        os.write(wfd, data)

        return len(data)
    else:
      with open(self._path, mode='rb') as rfd:
        bfd = os.open(bpath, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, mode=0o440)
        with open(bfd, mode='wb') as wfd:
          shutil.copyfileobj(rfd, wfd)

      return os.path.getsize(bpath)

tag(sres) classmethod

Build a cache tag from a stat result.

Parameters:

Name Type Description Default
sres

os.stat_result of the file.

required

Returns:

Type Description

The cache tag embedding size and modification time.

Source code in py_misc_utils/fs/file_fs.py
46
47
48
49
50
51
52
53
54
55
56
@classmethod
def tag(cls, sres):
  """Build a cache tag from a stat result.

  Args:
    sres: os.stat_result of the file.

  Returns:
    The cache tag embedding size and modification time.
  """
  return chf.make_tag(size=sres.st_size, mtime=sres.st_mtime)

support_blocks()

Return True since local files support direct block reads.

Source code in py_misc_utils/fs/file_fs.py
58
59
60
def support_blocks(self):
  """Return True since local files support direct block reads."""
  return True

read_block(bpath, offset, size)

Read a block of data from a file.

Parameters:

Name Type Description Default
bpath

Path of the file to read from.

required
offset

Offset in the file where reading starts.

required
size

Number of bytes to read.

required

Returns:

Type Description

The requested data as bytes.

Source code in py_misc_utils/fs/file_fs.py
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
def read_block(self, bpath, offset, size):
  """Read a block of data from a file.

  Args:
    bpath: Path of the file to read from.
    offset: Offset in the file where reading starts.
    size: Number of bytes to read.

  Returns:
    The requested data as bytes.
  """
  if offset != chf.CachedBlockFile.WHOLE_OFFSET:
    with (osfd.OsFd(self._path, os.O_RDONLY) as
          rfd, osfd.OsFd(bpath, os.O_CREAT | os.O_TRUNC | os.O_WRONLY,
                         mode=0o440) as wfd):
      if os.lseek(rfd, offset, os.SEEK_SET) != offset:
        alog.xraise(RuntimeError, f'Unable to seek {self._path} at offset {offset}')
      data = os.read(rfd, size)
      os.write(wfd, data)

      return len(data)
  else:
    with open(self._path, mode='rb') as rfd:
      bfd = os.open(bpath, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, mode=0o440)
      with open(bfd, mode='wb') as wfd:
        shutil.copyfileobj(rfd, wfd)

    return os.path.getsize(bpath)

FileFs

Bases: FsBase

FileSystem implementation for local paths.

It is the default backend and the reference implementation of the FsBase interface: every operation maps directly onto the os module calls of the same name.

Source code in py_misc_utils/fs/file_fs.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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
179
180
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
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
284
285
286
287
288
289
290
291
292
293
294
295
296
class FileFs(fsb.FsBase):
  """FileSystem implementation for local paths.

  It is the default backend and the reference implementation of the
  FsBase interface: every operation maps directly onto the os module
  calls of the same name.
  """

  ID = 'file'
  IDS = (ID,)

  def __init__(self, cache_iface=None, **kwargs):
    """Initialize the backend.

    Args:
      cache_iface: Optional cache interface used by inherited read
        operations; not needed since local files need no caching.
      **kwargs: Extra keyword arguments forwarded to FsBase.
    """
    super().__init__(cache_iface=cache_iface, **kwargs)

  def norm_url(self, url):
    """Normalize a local path.

    Args:
      url: The path to normalize.

    Returns:
      The normalized path, as per fs_utils.normpath().
    """
    return fsu.normpath(url)

  def _create_tag(self, sres):
    """Build the cache tag of a file from its stat result."""
    return FileReader.tag(sres)

  def stat(self, url):
    """Stat a path.

    Args:
      url: The path to stat.

    Returns:
      The DirEntry of the file, built from the os.stat result.
    """
    sres = os.stat(url)

    return fsb.DirEntry(name=os.path.basename(url),
                        path=url,
                        etag=self._create_tag(sres),
                        st_mode=sres.st_mode,
                        st_size=sres.st_size,
                        st_ctime=sres.st_ctime,
                        st_mtime=sres.st_mtime)

  def open(self, url, mode, **kwargs):
    """Open a local file.

    Args:
      url: The path of the file to open.
      mode: Open mode string.
      **kwargs: Extra open() keyword arguments; accepted for interface
        compatibility but not forwarded to the builtin open().

    Returns:
      The opened file object.
    """
    return open(url, mode=mode)

  def remove(self, url):
    """Remove a file.

    Args:
      url: The path of the file to remove.
    """
    os.remove(url)

  def rename(self, src_url, dest_url):
    """Rename a file or directory.

    Args:
      src_url: The source path.
      dest_url: The destination path.
    """
    os.rename(src_url, dest_url)

  def replace(self, src_url, dest_url):
    """Rename a file or directory, replacing the destination.

    Args:
      src_url: The source path.
      dest_url: The destination path.
    """
    os.replace(src_url, dest_url)

  def mkdir(self, url, mode=None):
    """Create a directory.

    Args:
      url: The path of the directory to create.
      mode: Optional permission mode (default: 0o777).
    """
    os.mkdir(url, mode=mode or 0o777)

  def makedirs(self, url, mode=None, exist_ok=None):
    """Create a directory and all its parents.

    Args:
      url: The path of the directory to create.
      mode: Optional permission mode (default: 0o777).
      exist_ok: If True, do not raise when the directory already exists
        (default: False).
    """
    os.makedirs(url, mode=mode or 0o777, exist_ok=exist_ok or False)

  def rmdir(self, url):
    """Remove an empty directory.

    Args:
      url: The path of the directory to remove.
    """
    os.rmdir(url)

  def rmtree(self, url, ignore_errors=None):
    """Recursively remove a directory tree.

    Args:
      url: The path of the directory tree to remove.
      ignore_errors: If True, errors raised while removing the tree are
        ignored (default: False).
    """
    fsu.safe_rmtree(url, ignore_errors=ignore_errors or False)

  def list(self, url):
    """Enumerate the entries of a directory.

    Args:
      url: The path of the directory to enumerate.

    Yields:
      A DirEntry for every file and subdirectory of the directory.
    """
    with os.scandir(url) as sdit:
      for de in sdit:
        sres = de.stat()

        yield fsb.DirEntry(name=de.name,
                           path=os.path.join(url, de.name),
                           etag=self._create_tag(sres),
                           st_mode=sres.st_mode,
                           st_size=sres.st_size,
                           st_ctime=sres.st_ctime,
                           st_mtime=sres.st_mtime)

  def put_file(self, url, data_gen):
    """Write data chunks into a file.

    Args:
      url: The path of the file to write.
      data_gen: Iterable of bytes chunks to write.
    """
    with open(url, mode='wb') as fd:
      fd.writelines(data_gen)

  def get_file(self, url):
    """Read the contents of a file as chunks.

    Args:
      url: The path of the file to read.

    Yields:
      The file contents as bytes chunks.
    """
    with open(url, mode='rb') as fd:
      yield from fsu.enum_chunks(fd)

  def as_local(self, url, **kwargs):
    """Return the path unchanged, since files are already local.

    Args:
      url: The path of the file.
      **kwargs: Extra keyword arguments, ignored.

    Returns:
      The url itself.
    """
    return url

  def link(self, src_url, dest_url):
    """Create a hard link.

    Args:
      src_url: The path of the existing file.
      dest_url: The path of the link to create.
    """
    os.link(src_url, dest_url)

  def symlink(self, src_url, dest_url):
    """Create a symbolic link.

    Args:
      src_url: The path of the existing file.
      dest_url: The path of the link to create.
    """
    os.symlink(src_url, dest_url)

norm_url(url)

Normalize a local path.

Parameters:

Name Type Description Default
url

The path to normalize.

required

Returns:

Type Description

The normalized path, as per fs_utils.normpath().

Source code in py_misc_utils/fs/file_fs.py
113
114
115
116
117
118
119
120
121
122
def norm_url(self, url):
  """Normalize a local path.

  Args:
    url: The path to normalize.

  Returns:
    The normalized path, as per fs_utils.normpath().
  """
  return fsu.normpath(url)

stat(url)

Stat a path.

Parameters:

Name Type Description Default
url

The path to stat.

required

Returns:

Type Description

The DirEntry of the file, built from the os.stat result.

Source code in py_misc_utils/fs/file_fs.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def stat(self, url):
  """Stat a path.

  Args:
    url: The path to stat.

  Returns:
    The DirEntry of the file, built from the os.stat result.
  """
  sres = os.stat(url)

  return fsb.DirEntry(name=os.path.basename(url),
                      path=url,
                      etag=self._create_tag(sres),
                      st_mode=sres.st_mode,
                      st_size=sres.st_size,
                      st_ctime=sres.st_ctime,
                      st_mtime=sres.st_mtime)

open(url, mode, **kwargs)

Open a local file.

Parameters:

Name Type Description Default
url

The path of the file to open.

required
mode

Open mode string.

required
**kwargs

Extra open() keyword arguments; accepted for interface compatibility but not forwarded to the builtin open().

{}

Returns:

Type Description

The opened file object.

Source code in py_misc_utils/fs/file_fs.py
147
148
149
150
151
152
153
154
155
156
157
158
159
def open(self, url, mode, **kwargs):
  """Open a local file.

  Args:
    url: The path of the file to open.
    mode: Open mode string.
    **kwargs: Extra open() keyword arguments; accepted for interface
      compatibility but not forwarded to the builtin open().

  Returns:
    The opened file object.
  """
  return open(url, mode=mode)

remove(url)

Remove a file.

Parameters:

Name Type Description Default
url

The path of the file to remove.

required
Source code in py_misc_utils/fs/file_fs.py
161
162
163
164
165
166
167
def remove(self, url):
  """Remove a file.

  Args:
    url: The path of the file to remove.
  """
  os.remove(url)

rename(src_url, dest_url)

Rename a file or directory.

Parameters:

Name Type Description Default
src_url

The source path.

required
dest_url

The destination path.

required
Source code in py_misc_utils/fs/file_fs.py
169
170
171
172
173
174
175
176
def rename(self, src_url, dest_url):
  """Rename a file or directory.

  Args:
    src_url: The source path.
    dest_url: The destination path.
  """
  os.rename(src_url, dest_url)

replace(src_url, dest_url)

Rename a file or directory, replacing the destination.

Parameters:

Name Type Description Default
src_url

The source path.

required
dest_url

The destination path.

required
Source code in py_misc_utils/fs/file_fs.py
178
179
180
181
182
183
184
185
def replace(self, src_url, dest_url):
  """Rename a file or directory, replacing the destination.

  Args:
    src_url: The source path.
    dest_url: The destination path.
  """
  os.replace(src_url, dest_url)

mkdir(url, mode=None)

Create a directory.

Parameters:

Name Type Description Default
url

The path of the directory to create.

required
mode

Optional permission mode (default: 0o777).

None
Source code in py_misc_utils/fs/file_fs.py
187
188
189
190
191
192
193
194
def mkdir(self, url, mode=None):
  """Create a directory.

  Args:
    url: The path of the directory to create.
    mode: Optional permission mode (default: 0o777).
  """
  os.mkdir(url, mode=mode or 0o777)

makedirs(url, mode=None, exist_ok=None)

Create a directory and all its parents.

Parameters:

Name Type Description Default
url

The path of the directory to create.

required
mode

Optional permission mode (default: 0o777).

None
exist_ok

If True, do not raise when the directory already exists (default: False).

None
Source code in py_misc_utils/fs/file_fs.py
196
197
198
199
200
201
202
203
204
205
def makedirs(self, url, mode=None, exist_ok=None):
  """Create a directory and all its parents.

  Args:
    url: The path of the directory to create.
    mode: Optional permission mode (default: 0o777).
    exist_ok: If True, do not raise when the directory already exists
      (default: False).
  """
  os.makedirs(url, mode=mode or 0o777, exist_ok=exist_ok or False)

rmdir(url)

Remove an empty directory.

Parameters:

Name Type Description Default
url

The path of the directory to remove.

required
Source code in py_misc_utils/fs/file_fs.py
207
208
209
210
211
212
213
def rmdir(self, url):
  """Remove an empty directory.

  Args:
    url: The path of the directory to remove.
  """
  os.rmdir(url)

rmtree(url, ignore_errors=None)

Recursively remove a directory tree.

Parameters:

Name Type Description Default
url

The path of the directory tree to remove.

required
ignore_errors

If True, errors raised while removing the tree are ignored (default: False).

None
Source code in py_misc_utils/fs/file_fs.py
215
216
217
218
219
220
221
222
223
def rmtree(self, url, ignore_errors=None):
  """Recursively remove a directory tree.

  Args:
    url: The path of the directory tree to remove.
    ignore_errors: If True, errors raised while removing the tree are
      ignored (default: False).
  """
  fsu.safe_rmtree(url, ignore_errors=ignore_errors or False)

list(url)

Enumerate the entries of a directory.

Parameters:

Name Type Description Default
url

The path of the directory to enumerate.

required

Yields:

Type Description

A DirEntry for every file and subdirectory of the directory.

Source code in py_misc_utils/fs/file_fs.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
def list(self, url):
  """Enumerate the entries of a directory.

  Args:
    url: The path of the directory to enumerate.

  Yields:
    A DirEntry for every file and subdirectory of the directory.
  """
  with os.scandir(url) as sdit:
    for de in sdit:
      sres = de.stat()

      yield fsb.DirEntry(name=de.name,
                         path=os.path.join(url, de.name),
                         etag=self._create_tag(sres),
                         st_mode=sres.st_mode,
                         st_size=sres.st_size,
                         st_ctime=sres.st_ctime,
                         st_mtime=sres.st_mtime)

put_file(url, data_gen)

Write data chunks into a file.

Parameters:

Name Type Description Default
url

The path of the file to write.

required
data_gen

Iterable of bytes chunks to write.

required
Source code in py_misc_utils/fs/file_fs.py
246
247
248
249
250
251
252
253
254
def put_file(self, url, data_gen):
  """Write data chunks into a file.

  Args:
    url: The path of the file to write.
    data_gen: Iterable of bytes chunks to write.
  """
  with open(url, mode='wb') as fd:
    fd.writelines(data_gen)

get_file(url)

Read the contents of a file as chunks.

Parameters:

Name Type Description Default
url

The path of the file to read.

required

Yields:

Type Description

The file contents as bytes chunks.

Source code in py_misc_utils/fs/file_fs.py
256
257
258
259
260
261
262
263
264
265
266
def get_file(self, url):
  """Read the contents of a file as chunks.

  Args:
    url: The path of the file to read.

  Yields:
    The file contents as bytes chunks.
  """
  with open(url, mode='rb') as fd:
    yield from fsu.enum_chunks(fd)

as_local(url, **kwargs)

Return the path unchanged, since files are already local.

Parameters:

Name Type Description Default
url

The path of the file.

required
**kwargs

Extra keyword arguments, ignored.

{}

Returns:

Type Description

The url itself.

Source code in py_misc_utils/fs/file_fs.py
268
269
270
271
272
273
274
275
276
277
278
def as_local(self, url, **kwargs):
  """Return the path unchanged, since files are already local.

  Args:
    url: The path of the file.
    **kwargs: Extra keyword arguments, ignored.

  Returns:
    The url itself.
  """
  return url

Create a hard link.

Parameters:

Name Type Description Default
src_url

The path of the existing file.

required
dest_url

The path of the link to create.

required
Source code in py_misc_utils/fs/file_fs.py
280
281
282
283
284
285
286
287
def link(self, src_url, dest_url):
  """Create a hard link.

  Args:
    src_url: The path of the existing file.
    dest_url: The path of the link to create.
  """
  os.link(src_url, dest_url)

Create a symbolic link.

Parameters:

Name Type Description Default
src_url

The path of the existing file.

required
dest_url

The path of the link to create.

required
Source code in py_misc_utils/fs/file_fs.py
289
290
291
292
293
294
295
296
def symlink(self, src_url, dest_url):
  """Create a symbolic link.

  Args:
    src_url: The path of the existing file.
    dest_url: The path of the link to create.
  """
  os.symlink(src_url, dest_url)