Nov-25-2018, 11:57 AM
(This post was last modified: Nov-25-2018, 03:43 PM by Gribouillis.)
Larz60+ Wrote:I am curious if os now uses PyFilesystem as there are new commands like os.fspath that use the fs prefix.No Python itself doesn't depend on a third party module such as PyFileSystem. The role of PyFileSystem is to offer a unified API for different objects, so that the same code can be used in different contexts. Consider a slightly better version of the above code
from dictfs import DictFs def fill(root): d = root.makedirs('Boston/Restaurants/Spoke Wine Bar') d.settext('Addr1', '89 Holland St') d.settext('City', 'Sommerville') d.settext('ZipCode', '02144') d.settext('Phone', '617-718-9463') d = root.makedirs('Boston/Restaurants/Highland Kitchen') d.settext('Addr1', '150 Highland Ave') d.settext('City', 'Sommerville') d.settext('ZipCode', '02144') d.settext('Phone', '617-625-1131') def main(): with DictFs() as root: fill(root) root.tree() if __name__ == '__main__': main()
Output:└── Boston
└── Restaurants
├── Highland Kitchen
│ ├── Addr1
│ ├── City
│ ├── Phone
│ └── ZipCode
└── Spoke Wine Bar
├── Addr1
├── City
├── Phone
└── ZipCode
This code acts in memory on a python dictionary. I only need to replace DictFs()
by fs.osfs.OSFS('/tmp')
or fs.tarfs.TarFS('foo.tgz', write=True)
to have the same code operate on a directory on disk or a gunzipped tar file. The same code can manipulate a remote FTP or dropbox hierarchy.Of course, it may remain some filesystem specific code, for example if I want to call
root.as_dict()
, which is defined only for my DictFs
class, but clearly, using the unified API, it would be quite easy to define a function as_dict
that would apply to any of these filesystems. PyFileSystem is a great step towards code reusability!