转载: Discovering Python 3’s pathlib – Dante’s Python musings
The pathlib is one of the new features in Python 3 I loved immediatly when I recognized it’s advantages. The pathlib a sort of a swiss knife tool and more than capable to replace os.path because it gives object orientated programming a reason. Especially for configuration purposes the pathlib is handy:
1 | from pathlib import Path |
The slash as an operator avoids brackets to join paths and makes the code very simplistic. But here doesn’t the advantage:
1 | '/home/dante') path1 = Path( |
Of course fundamental operations like file IO and file name attributes are available:
1 | '*.conf)) config_files = config_dir.glob( |
Every Path object linked to a file is able to open this file:
1 | 'project.conf') config_file = config_dir / Path( |
But reading a file can be even shorter:
1 | 'project.conf') config_file = config_dir / Path( |
Python 3’s pathlib is able to supersede os.path with ease. The OOP approach makes working with this library fun.