fs – Files, Directories, &c.

Introduction

The fs module makes it easy to work with files, directories, drives, volumes and paths within the Windows filesystems. The most common entry-point is to use entry() to return a File or Dir object, although you can use file() or dir() directly. Instances of these classes need not exist on any filesystem – in fact they equate to True or False according to the existence or not of a corresponding filesystem object. But they can be the source or target of all the usual filesystem operations. In common with other modules in this package, functionality is provided at the module level as well as at the class level, so you can, eg, call File.copy() or copy() to copy a file to another location.

An important part of the module is the FilePath class which eases manipulation of filesystem paths and is at the same time a subclass of unicode, so is accepted in system calls where strings are expected.

Functions

Factories

entry(filepath, _file_info=<Unset>)

Return a File or Dir object representing this filepath.

filepath Result
None or “” None
an Entry or subclass object the same object
an existing file name a File object representing that file
an existing directory name a Dir object representing that directory
a file name which doesn’t exist a Dir if filepath ends with \, File otherwise
file(filepath)

Return a File object representing this filepath on the filepath. If filepath is already a File object, return it unchanged otherwise ensure that the filepath doesn’t point to an existing directory and return a File object which represents it.

dir(filepath)

Return a Dir object representing this filepath on the filepath. If filepath is already a Dir object, return it unchanged otherwise ensure that the filepath doesn’t point to an existing file and return a Dir object which represents it.

drive(drive)

Return a Drive object representing drive

drive Result
None None
an Drive or subclass object the same object
a drive letter a Drive object
volume(volume)

Return a Volume object corresponding to volume

volume Result
None None
an Volume or subclass object the same object
a volume name \\?\Volume... a Volume object representing that volume
a directory name a Volume object representing the volume at that mountpoint

stdlib Extras

Several functions are either convenient or superior replacements to equivalent stdlib functionality.

listdir(d)

Mimic the built-in os.list functionality as a generator, optionally ignoring access errors.

Parameters:d – anything accepted by dir()
Returns:yield the name of each file in directory d
glob(pattern)

Mimic the built-in glob.glob functionality as a generator, optionally ignoring access errors.

Parameters:pattern – passed to files()
Returns:yields a FilePath object for each matching file
mkdir(dirpath, *args, **kwargs)

Mimic os.mkdir, implemented via Dir.create()

rmdir(filepath, recursive=False)

Mimic the os.rmdir functionality, optionally recursing

Parameters:
walk(root, depthfirst=False, error_handler=None)

Walk the directory tree starting from root, optionally ignoring access errors.

Parameters:
Returns:

as Dir.walk()

flat(root, pattern='*', includedirs=False, depthfirst=False, error_handler=None)

Iterate over a flattened version of the directory tree starting from root. Implemented via Dir.flat().

Parameters:
Returns:

as Dir.flat()

move(source_filepath, *args, **kwargs)

Move one Entry object to another, implemented via File.move() or Dir.move()

Parameters:source_filepath – anything accepted by entry()
copy(source_filepath, *args, **kwargs)

Copy one Entry object to another, implemented via File.copy() or Dir.copy()

Parameters:source_filepath – anything accepted by entry()
delete(filepath)

Deletes a Entry object, implemented via File.delete() or Dir.delete()

Parameters:filepath – anything accepted by entry()
exists(filepath)

Mimic os.path.exists, implemented via the Entry boolean mechanism

Parameters:filepath – anything accepted by entry()
Returns:True if filepath exists, False otherwise
zip(filepath, *args, **kwargs)

Create and return a zip archive of filepath, implemented via File.zip() or Dir.zip()

Parameters:filepath – anything accepted by entry()
touch(filepath)

Update a file’s modification time, creating it if it does not exist, implemented via File.create()

Parameters:filepath – anything accepted by file()

Helpers

get_parts(filepath)

Helper function to regularise a file path and then to pick out its drive and path components.

Attempt to match the first part of the string against known path leaders:

<drive>:\
\\?\<drive>:\
\\?\Volume{xxxx-...}\
\\server\share\

If that fails, assume the path is relative.

Path Parts
c:/ [“c:\”, “”]
c:/t [“c:\”, “t”]
c:/t/ [“c:\”, “t”]
c:/t/test.txt [“c:\”, “t”, “test.txt”]
c:/t/s/test.txt [“c:\”, “t”, “s”, “test.txt”]
c:test.txt [“c:”, “test.txt”]
s/test.txt [“”, “s”, “test.txt”]
\\server\share [“\\server\share\”, “”]
\\server\share\a.txt [“\\server\share\”, “a.txt”]
\\server\share\t\a.txt [“\\server\share\”, “t”, “a.txt”]
\\?\c:test.txt [“\\?\c:\”, “test.txt”]
\\?\Volume{xxxx-..}\t.txt [“\\?Volume{xxxx-..}\”, “t.txt”]

The upshot is that the first item in the list returned is always the root, one of: a slash-terminated drive/volume/share for an absolute path; an empty string for a relative path; or a drive-colon for a drive-relative path.

All other items before the last one represent the directories along the way. The last item is the filename or directory name.

The original filepath can usually be reconstructed as:

from winsys import fs
filepath = "c:/temp/abc.txt"
parts = fs.get_parts (filepath)
assert parts[0] + "\\".join (parts[1:]) == filepath

The exception is when a root (UNC or volume) is given without a trailing slash. This is added in. Or if a directory is given with a trailing slash. This is stripped off.

normalised(filepath)

Convert any path or path-like object into the length-unlimited unicode equivalent. This should avoid issues with maximum path length and the like.

handle(filepath, write=False, async=False, attributes=None, sec=None)

Return a file handle either for querying (the default case) or for writing – including writing directories

Parameters:
  • filepath – anything whose unicode representation is a valid file path
  • write – is the handle to be used for writing [True]
  • attributes – anything accepted by FILE_ATTRIBUTE
Returns:

an open file handle for reading or writing, including directories

relative_to(filepath1, filepath2)

Return filepath2 relative to filepath1. Both names are normalised first.

filepath1 filepath2 result
c:/a/b.txt c:/a b.txt
c:/a/b/c.txt c:/a b/c.txt
c:/a/b/c.txt c:/a/b c.txt
Parameters:
  • filepath1 – a file or directory
  • filepath2 – a directory
Returns:

filepath2 relative to filepath1

attributes(filepath)

Return an _Attributes object representing the file attributes of filepath, implemented via Entry.attributes()

Parameters:filepath – anything accepted by entry()
Returns:an _Attributes object

Additional Filesystem Operations

mount(filepath, vol)

Mount vol at filepath, implemented via Dir.mount()

Parameters:
dismount(filepath)

Dismount the volume at filepath, implemented via Dir.dismount()

Parameters:filepath – anything accepted by dir()
drives()

Iterate over all the drive letters in the system, yielding a Drive object representing each one.

volumes()

Iterate over all the volumes in the system, yielding a Volume object representing each one.

mounts()

Iterate over all mounted volume mountpoints in the system, yielding a (Dir, Volume) pair for each one, eg:

from winsys import fs
drive_volumes = dict (fs.mounts ())
watch(root, subdirs=False, watch_for=287, buffer_size=8192)

Return an iterator which returns a file change on every iteration. The file change comes in the form: action, old_filename, new_filename. action is one of the FILE_ACTION constants, while the filenames speak for themselves. The filenames will be the same if the file has been updated. If the file is new, old_filename will be None; if it has been deleted, new_filename will be None; if it has been renamed, they will be different:

from winsys import fs
watcher = fs.watch ("c:/temp", subdirs=True)
for action, old_filename, new_filename in watcher:
  if action == fs.FILE_ACTION.ADDED:
    print new_filename, "added"
  elif action == fs.FILE_ACTION.REMOVED:
    print old_filename, "removed"

Classes

class _Attributes(flags=0, const=<Constants: {'TEMPORARY': 256, 'OFFLINE': 4096, 'NORMAL': 128, 'ENCRYPTED': 16384, 'SYSTEM': 4, 'VIRTUAL': 65536, 'NOT_CONTENT_INDEXES': 8192, 'READONLY': 1, 'COMPRESSED': 2048, 'DIRECTORY': 16, 'HIDDEN': 2, 'SPARSE_FILE': 512, 'ARCHIVE': 32, 'REPARSE_POINT': 1024}>)

Simple class wrapper for the list of file attributes (readonly, hidden, &c.) It can be accessed by attribute access, item access and the “in” operator:

from winsys import fs
attributes = fs.file (fs.__file__).parent ().attributes
assert (attributes.directory)
assert (attributes[fs.FILE_ATTRIBUTE.DIRECTORY])
assert ("directory" in attributes)

Constants

Exceptions

exception x_fs(errno=None, errctx=None, errmsg=None)

Base for all fs-related exceptions

exception x_no_such_file(errno=None, errctx=None, errmsg=None)

Raised when a file could not be found

exception x_too_many_files(errno=None, errctx=None, errmsg=None)

Raised when more than one file matches a name

exception x_invalid_name(errno=None, errctx=None, errmsg=None)

Raised when a filename contains invalid characters

exception x_no_certificate(errno=None, errctx=None, errmsg=None)

Raised when encryption is attempted without a certificate

exception x_not_ready(errno=None, errctx=None, errmsg=None)

Raised when a device is not ready

References

See also

Using the fs module
Cookbook examples of using the fs module

Table Of Contents

Previous topic

event_logs – Event Logs

Next topic

The Drive class

This Page