fspath.fspath module¶
semantic path names and much more
- class fspath.fspath.FSPath(pathname)[source]¶
Bases:
str
A path name to a file or folder.
Handling path names more comfortable, e.g.:
concatenate path names with the division operator
/
call functions like mkdir on path names
get properties like EXISTS
>>> from fspath import FSPath >>> tmp = FSPath('~/tmp') >>> tmp '/home/user/tmp' >>> tmp.EXISTS False
no additional import, no juggling with
os.join(...)
simply slash
/
andfoo.<method>
calls>>> [(tmp/x).makedirs() for x in ('foo', 'bar')] True, True >>> for n in tmp.listdir(): ... print(tmp / n) ... /home/user/tmp/foo /home/user/tmp/bar
downloads & archives
>>> arch = foo / 'fspath.zip' >>> url = 'https://github.com/return42/fspath/archive/master.zip'
download
– super easy download + segmentation + nice ticker>>> arch.download(url, chunksize=1024, ticker=True) /home/user/tmp/foo/fspath.zip: [87.9 KB][=============== ] 83%
FSPath.extract
– extract in one step, no matter ZIP or TAR>>> arch.ISTAR, arch.ISZIP (False, True) >>> arch.extract(foo) ['fspath-master/', 'fspath-master/.gitignore' , 'fspath-master/MAINFEST.in', 'fspath-master/Makefile' , 'fspath-master/README.rst', ... ]
For more examples see our slide-show.
- property ABSPATH¶
The absolute pathname
E.g:
../to/../to/folder/filename.ext
–>/path/to/folder/filename.ext
- property ATIME¶
Return the last access time, reported by os.stat().
- property BASENAME¶
The path name with suffix, but without the folder name.
E.g.:
/path/to/folder/filename.ext
–>filename.ext
- property CTIME¶
Return the metadata change time, reported by os.stat().
- property DIRNAME¶
The path name of the folder, where the file is located
E.g.:
/path/to/folder/filename.ext
–>/path/to/folder
- property EXECUTABLE¶
True if file is executable
- property EXISTS¶
True if file/pathname exist
- property EXPANDUSER¶
Path with an initial component of ~ or ~user replaced by that user’s home.
- property EXPANDVARS¶
Path with environment variables expanded.
- property FILENAME¶
The path name without folder and suffix.
E.g.:
/path/to/folder/filename.ext
–>filename
- property ISABSPATH¶
True if path is absolute
- property ISDIR¶
True if path is a folder
- property ISFILE¶
True if path is a file
- property ISLINK¶
True if path is a symbolic link
- property ISMOUNT¶
True if path is a mountpoint
- property ISTAR¶
True if path is a TAR archive file
- property ISZIP¶
True if path is a ZIP file
- property MTIME¶
Return the last modification time, reported by os.stat().
- property NTPATH¶
The path name in the Windows (NT) notation.
- OS = {'altsep': None, 'curdir': '.', 'defpath': '/bin:/usr/bin', 'devnull': '/dev/null', 'extsep': '.', 'linesep': '\n', 'pathsep': ':', 'sep': '/'}¶
- property POSIXPATH¶
The path name in POSIX notation.
Helpfull if you are on MS-Windows and need the POSIX name.
- Popen(*args, **kwargs)[source]¶
Get a
subprocess.Popen
object (proc
).The path name of the self-object is the programm to call. The program arguments are given py
*args
and the*kwargs
are passed to thesubprocess.Popen
constructor. Theuniversal_newlines=True
is true by default.see https://docs.python.org/3/library/subprocess.html#popen-constructor
from fspath import FSPath proc = FSPath("arp").Popen("-a",) stdout, stderr = proc.communicate() retVal = proc.returncode print("stdout: %s" % stdout) print("stderr: %s" % stderr) print("exit code = %d" % retVal)
- property READABLE¶
True if file/path is readable
- property REALPATH¶
The real pathname without symbolic links.
- property SIZE¶
Size in bytes
- property SKIPSUFFIX¶
The complete file name without suffix.
E.g.:
/path/to/folder/filename.ext
–>/path/to/folder/filename
- property SUFFIX¶
The filename suffix
E.g.:
/path/to/folder/filename.ext
–>.ext
- property VALUE¶
string of the path name
- property WRITEABLE¶
True if file/path is writeable
- copyfile(dest, preserve=False)[source]¶
Copy the file src to the file or directory dest.
- Dest str:
The destination may be a directory
- Preserve bool:
copies permission bits
- download(url, chunksize=1048576, ticker=False, pipe=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Download URL into file
The default chunksize is 1048576 Bytes, with ticker=True an progress-bar is prompted.
E.g. to download FSPath’s README.rst with a progressbar on stdout:
url = "https://raw.githubusercontent.com/return42/fspath/master/README.rst" readme = FSPath("README.rst") readme.download(url, ticker=True)
- extract(folder='.', pwd=None, ticker=False, pipe=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Extract TAR or ZIP archive to ‘folder’
Uses
extractall
fromtarfile.TarFile
andzipfile.Zipfile
to extract intofolder
.- Folder str:
folder to extract into
- Pwd str:
password for crypted (only ZIP)
- Returns:
members in an iterable form (list or just iterator)
- glob(pattern, relpath=False)[source]¶
Return an iterator which yields the paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by ‘*’ and ‘?’ patterns.
- makedirs(mode=509)[source]¶
Recursive directory creation, default mode is 0o775 (octal).
- Parameters:
mode (int) – file permissons
- Returns:
created (True) already exists (True),
- Raises:
Exception – in case of errors (permissons, etc.)
- openBinaryFile(mode='rb', errors='strict', buffering=None)[source]¶
Open file as binary file.
wraps io.open:
except argument
closefd
(meaningless when using filenames)except argument
encoding
(meaningless since binary)except argument
newline
(meaningless since binary)mode='rb'
is default
- openTextFile(mode='rt', encoding='utf-8', errors='strict', buffering=1, newline=None)[source]¶
Open file as text file.
wraps io.open:
except argument
closefd
(meaningless when using filenames)encoding='utf-8'
is defaultmode='rt'
is defaultbuffering=1
is default (selects line buffering)
- reMatchFind(name, use_files=True, use_dirs=True, followlinks=False, relpath=False)[source]¶
Returns iterator which yields matching path names
- Parameters:
use_files – iterator includes names of files
use_dirs – iterator includes names of folders
followlinks – follow symbolic links
To find all C and header files use:
folder.reMatchFind("*\.[ch]")
To find the first C or header file use:
next(myFolder.reMatchFind("*\.[ch]"), None)
- splitpath()[source]¶
Split a pathname.
Return tuple (head, tail) where tail is everything after the final slash. Either part may be empty.
- walk(topdown=True, onerror=None, followlinks=False)[source]¶
Directory tree generator.
For each directory in the directory tree rooted at top (including top itself, but excluding ‘.’ and ‘..’), yields a 3-tuple:
folder, dirnames, filenames
dirnames is a list of the names of the subdirectories in dirpath (excluding ‘.’ and ‘..’). filenames is a list of the names of the non-directory files in dirpath.
Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do
folder / name
.By default, os.walk does not follow symbolic links to subdirectories on systems that support them. In order to get this functionality, set the optional argument ‘followlinks’ to true.
Caution
If you pass a relative pathname for top, don’t change the current working directory between resumptions of walk. walk never changes the current directory, and assumes that the client doesn’t either.
For more details see
os.walk
- fspath.fspath.callEXE(cmd, *args, **kwargs)[source]¶
Synchronous command call
cmd
with arguments*args
.The
*kwargs
are passed to thesubprocess.Popen
constructor. The return value is a three-digit tuple(stdout, stderr, rc)
.from fspath import callEXE out, err, rc = callEXE("arp", "-a") print("stdout: %s" % out) print("stderr: %s" % err) print("exit code = %d" % rc)