Package: pyfs
An easy to use file system wrapper for Python that aims to simplify os,
os.path, os.walk, shutils, fnmatch, etc.InstallationInstall with the Python Package Managerpipwith the following
command:pipinstallpyfsOr install from source:gitclonehttps://github.com/chaosmail/python-fs.gitcdpython-fspythonsetup.pyinstallDocumentationFirst, import the python-fs module.importfsfs.exists(path)Returns True if thepathexists. Returns False ifpathdoes not
exist.>>>fs.exists('test.txt')True>>>fs.exists('some_directory')Truefs.isfile(path)Returns True if thepathexists and is a file. Returns False ifpathis a directory or does not exist.>>>fs.isfile('test.txt')True>>>fs.isfile('some_directory')Falsefs.isdir(path)Returns True if thepathexists and is a directory. Returns False ifpathis a file or does not exist.>>>fs.isdir('test.txt')False>>>fs.isdir('some_directory')Truefs.stat(path)Returns astats
objectthat
contains meta data ofpathwhere path can be either a file or
directory. RaisesOSErrorexception ifpathdoes not exist.>>>s=fs.stat('test.txt')>>>s.st_atime1428162423.839133>>>s.st_mtime1427919315.960152>>>s.st_ctime1427919315.960152fs.ctime(path)Platform dependent; returns time of most recent metadata change on Unix,
or the time of creation on Windows ofpathwhere path can be either a
file or directory. RaisesOSErrorexception ifpathdoes not exist.>>>fs.ctime('test.txt')1427919315.960152fs.atime(path)Returns time of most recent access ofpathwhere path can be either a
file or directory. RaisesOSErrorexception ifpathdoes not exist.>>>fs.atime('test.txt')1428162423.839133fs.mtime(path)Returns time of most recent content modification ofpathwhere path
can be either a file or directory. RaisesOSErrorexception ifpathdoes not exist.>>>fs.mtime('test.txt')1427919315.960152fs.mode(path)Returns permission mode ofpathwhere path can be either a file or
directory. RaisesOSErrorexception ifpathdoes not exist.>>>fs.mode('test.txt')33252fs.rename(oldPath, newPath)RenamesoldPathto newnewPathwhereoldPathcan be either a file
or directory. RaisesOSErrorexception ifoldPathdoes not exist.>>>fs.rename('old_test.txt','new_test.txt')>>>fs.rename('old_directory','new_directory')fs.truncate(path)Removes all files from thepathdirectory.>>>fs.truncate('some_directory')fs.chdir(path)Changes the current directory topath.>>>fs.chdir('some_directory')fs.chown(path, user=None, group=None)Changes the ownership of a pathpathto the owneruserand groupgroup. IfuserorgroupisNone, the permission for this user or
group stays unchanged. RaisesPermissionErrorexception if the current
user is not allowed to change the permission. RaisesKeyErrorexception if the user or group don’t exist. RaisesFileNotFoundErrorifpathdoes not exist.>>>fs.chown('some_directory',user='ckoerner')>>>fs.chown('/var/www',group='www-data')fs.chmod(path, mode, op=’+’)Sets the permissionsmodeof a pathpath.>>>fs.chmod('some_directory',0o755)Example:Add exectuable permission to a script run.sh>>>importstat>>>fs.chmod('run.sh',fs.mode('run.sh')|stat.S_IEXEC)Example:Set a 644 permission for a file keys.pem>>>fs.chmod('keys.pem',0o644)fs.addpath(path)Adds pathpathto the system path, so that modules can be imported
from this path.>>>fs.addpath('/foo/bar')>>>importfoofs.link(srcPath, destPath)Creates a hard link fromsrcPathtodestPath.>>>fs.link('/some/dir','linkhere')fs.symlink(srcPath, destPath)Creates a symbolic link fromsrcPathtodestPath.>>>fs.symlink('/some/dir/file','symlinkhere')fs.cwd()Get the current working directory.>>>fs.cwd()'/path/to/directory'fs.home()Get the current home directory.>>>fs.home()'/home/ckoerner'fs.abspath(path)Returns the absolute path from a relativepathwherepathcan be
either file or directory. Raises aValueErrorif the directorypathdoes not exist.>>>fs.abspath('test.txt')'/path/to/file/test.txt'>>>fs.abspath('some_directory')'/path/to/file/some_directory'fs.normalize(path)Returns the normalized path from apathwherepathcan be either
file or directory.>>>fs.normalize('test_dir/../test/test.txt')'test/test.txt'fs.rm(path)Deletes the filepath. Raises anOSErrorexception if the file does
not exist orpathis a directory.>>>fs.rm('test.txt')The Unix-likefs.unlinkis the same asfs.rm.fs.rmdir(path, recursive=True)Deletes the directorypathwith all containing files and directories.
Raises anOSErrorexception if the directory does not exist orpathis a file.>>>fs.rmdir('some_directory')fs.rmfiles(paths)Deletes an array of filespaths. Raises anOSErrorexception if a
file does not exist or an element ofpathsis a directory.>>>fs.rmfiles(['test.txt','another_file.txt'])Example:Remove all files from the current directory:>>>fs.rmfiles(fs.list())Example:Remove all .pyc files from a directory:>>>fs.rmfiles(fs.find('*.pyc'))fs.rmdirs(paths, recursive=True)Deletes an array of directoriespathswith all containing files and
directories. Raises anOSErrorexception if a directory does not exist
or an element ofpathsis a file.>>>fs.rmdirs(['some_directory','some_other_dir'])Example:Remove all directories from the current directory:>>>fs.rmdirs(fs.listdirs())Example:Remove all directories that start with local_:>>>fs.rmdirs(fs.finddirs('local_*'))fs.touch(path)Sets the modification timestamp ofpathto the current time or creates
the file ifpathdoes not exist. Directories not supported on Windows.>>>fs.touch('test.txt')fs.list(path=’.’)Generator that returns all files that are contained in the directorypath. Raises anOSErrorexception if the directorypathdoes not
exist.>>>files=fs.list()>>>list(files)['test.txt']>>>files=fs.list('some_directory')>>>list(files)['/path/to/dir/some_directory/another_test.txt']Example:Loop over all files in the current directory:>>>forfilenameinfs.list():passfs.listdirs(path=’.’)Generator that returns all directories that are contained in the
directorypath. Raises anOSErrorexception if the directorypathdoes not exist.>>>dirs=fs.listdirs()>>>list(dirs)['some_directory']>>>dirs=fs.listdirs('some_directory')>>>list(dirs)[]Example:Loop over all directories in the current directory:>>>fordirnameinfs.listdirs():passfs.find(pattern, path=’.’, exclude=None, recursive=True)Generator that returns all files that matchpatternand are contained
in the directorypath. Bothpatternandexcludecan beUnix
shell-style
wildcardsor
arrays of wildcards. Raises anOSErrorexception if the directorypathdoes not exist.>>>files=fs.find('*.txt')>>>list(files)['/path/to/file/test.txt','/path/to/file/some_directory/another_test.txt']>>>files=fs.find('*.txt',exclude='another*')>>>list(files)['/path/to/file/test.txt']Example:Loop over all .csv files in the current directory:>>>forfilenameinfs.find('*.csv',recursive=False):passExample:Loop over all .xls and .xlsx files in the current directory
and all sub-directories:>>>forfilenameinfs.find(['*.xls','*.xlsx']):passExample:Loop over all .ini files in the config directory and all
sub-directories except the ones starting with local_:>>>forfilenameinfs.find('*.ini',path='config',exclude='local_*'):passExample:Find and get the Vagrantfile in the config directory:>>>filename=next(fs.find('Vagrantfile',path='config'),None)Example:Find the latest SQL file in the backups directory:>>>filename=max(fs.find('*.sql',path='backup'),key=fs.ctime)fs.finddirs(pattern, path=’.’, exclude=None, recursive=True)Generator that returns all directories that matchpatternand are
contained in the directorypath. Bothpatternandexcludecan beUnix shell-style
wildcardsor
arrays of wildcards. Raises anOSErrorexception if the directorypathdoes not exist.>>>dirs=fs.finddirs('some*')>>>list(dirs)['/path/to/file/some_directory']>>>dirs=fs.finddirs('some*',exclude='*directory')>>>list(dirs)[]Example:Loop over all .git directories in the current directory and
all subdirectories:>>>fordirinfs.finddirs('.git'):passfs.open(path, mode=’r’)Returns afile
objectof a filepath. Raises anIOErrorexception if the filepathdoes
not exist.>>>file=fs.open('text.txt')Example:Loop through the lines of a file>>>file=fs.open('config.ini','r')>>>forlineinfile:passfs.write(path, content, encoding=’UTF-8’, append=False, raw=False)Writes the contentcontentof a filepath.>>>fs.write('text.txt','test')Example:Append content to a file>>>fs.write('text.txt','test',append=True)Example:Download an image from an url using
`requests <http://docs.python-requests.org/en/latest/>`__ and save it to
local disc:>>>importrequests>>>res=requests.get(url,stream=True)>>>fs.write(path,res.raw,raw=True)fs.read(path, encoding=’UTF-8’)Reads and returns the content of a filepath. Raises anIOErrorexception if the filepathdoes not exist.>>>fs.read('text.txt')u'test'fs.put(path, obj)Writes an objectobjto a filepath. Raises anIOErrorexception
if the filepathdoes not exist.>>>fs.put('array.dat',[1,2,3,4])Example:Save a trained SVM classifier using
`sklearn <http://scikit-learn.org/>`__ to local disc:>>>fromsklearnimportsvm>>>X=[[0,0],[1,1]]>>>y=[0,1]>>>clf=svm.SVC()>>>clf.fit(X,y)SVC(C=1.0,cache_size=200,class_weight=None,coef0=0.0,degree=3,gamma=0.0,kernel='rbf',max_iter=-1,probability=False,random_state=None,shrinking=True,tol=0.001,verbose=False)>>>fs.put('svm.dat',clf)fs.get(path, encoding=’UTF-8’)Reads and returns an object from a filepath. Raises anIOErrorexception if the filepathdoes not exist.>>>fs.get('array.dat')[1,2,3,4]Example:Read a trained SVM classifier using
`sklearn <http://scikit-learn.org/>`__ from local disc:>>>clf=fs.get('svm.dat')>>>clf.predict([[2.,2.]])array([1])fs.sepThe character used by the operating system to separate pathname
components. This is ‘/’ for POSIX and ‘\' for Windows.>>>fs.sep'/'fs.join(paths)Joins an array ofpartswithfs.sep.>>>fs.join([fs.sep,'path','to','directory'])'/path/to/directory'Additionally, you can also pass the path elements as argumentsfs.join(path, path, …).>>>fs.join(fs.sep,'path','to','directory')'/path/to/directory'fs.extname(path)Returns the extension name of a filepath.>>>fs.extname('/path/to/file/test.txt')'.txt'fs.basename(path, ext=””)Returns the base name of a filepath.>>>fs.basename('/path/to/file/test.txt')'test.txt'>>>fs.basename('/path/to/file/test.txt','.txt')'test'fs.dirname(path)Returns the directory name of a filepath.>>>fs.dirname('/path/to/file/test.txt')'/path/to/file'fs.add_suffix(path, suffix=””)Adds suffix to filenamepathand returns the new filename.>>>fs.add_suffix('/path/to/file/test.txt',suffix='_new')'/path/to/file/test_new.txt'fs.add_prefix(path, prefix=””)Adds prefix to filenamepathand returns the new filename.>>>fs.add_prefix('/path/to/file/test.txt',prefix='new_')'/path/to/file/new_test.txt'Changelog0.0.8Added fs.add_suffix() and fs.add_prefix()0.0.7Added fs.addpath() to add a path to the system pathAdded fs.basename(path, ext=False) to automatically return filename
without extension0.0.6Added fs.home() to retrieve the home directoryAdded fs.chown(), fs.chmod(), fs.link() and fs.symlink()Added fs.mode() as shortcut for fs.stat(path).st_modeAdded fs.cd() alias for fs.chdir()0.0.5Added fs.put() to store object to discAdded fs.get() to load object from disc0.0.4Fixed errors with fs.find() for recurive=FalseAdded tests for fs.find() and fs.finddirs()Added coverage badge0.0.3Fixed python3 error with fs.read()Added tests for fs.write() and fs.read()0.0.2Fixed installation error from missing README.md file0.0.1Initial upload to PyPiLicenseThis software is provided under the MIT License.