Archive
moving from unipath to pathlib
Unipath is a very nice 3rd-party library for an object-oriented approach to Python file/directory operations. Just look at this sane API:
>>> from unipath import Path >>> p = Path("/usr/lib/python2.5/gopherlib.py") >>> p.parent Path("/usr/lib/python2.5") >>> p.name Path("gopherlib.py") >>> p.ext '.py' >>> p.stem Path('gopherlib') >>> q = Path(p.parent, p.stem + p.ext) >>> q Path('/usr/lib/python2.5/gopherlib.py') >>> q == p True
However, a very similar module landed in Python 3 called pathlib. It is almost the same as unipath but since it’s in the standard library, I think I’ll switch to it. It means one less external dependency, which is always a good thing.
Let’s see what it looks like:
>>> from pathlib import Path >>> p = Path("/usr/lib/python2.5/gopherlib.py") >>> p.parent PosixPath('/usr/lib/python2.5') >>> p.name 'gopherlib.py' >>> p.suffix # !!! called suffix, not ext !!! '.py' >>> p.stem 'gopherlib' >>> q = Path(p.parent, p.stem + p.suffix) >>> q PosixPath('/usr/lib/python2.5/gopherlib.py') >>> q == p True >>>
One important difference though. Unipath’s Path is a subclass of str, thus whenever a function needs a string, you can pass a Path object. However, it’s not true for pathlib’s PosixPath. It means that if you need the string representation of a PosixPath, you need to convert it manually.
Example:
>>> import os >>> from pathlib import Path >>> p = Path("/usr/lib/python2.5/gopherlib.py") >>> os.path.exists(p) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.5/genericpath.py", line 19, in exists os.stat(path) TypeError: argument should be string, bytes or integer, not PosixPath >>> os.path.exists(str(p)) # here False >>>
Some other features
>>> from pathlib import Path >>> Path.home() PosixPath('/home/jabba') # Were you also fed up with os.path.expanduser('~') ? >>> p = Path('/tmp/na.txt') >>> p.chmod(0o644) >>> p.exists() True >>> p.is_file() True >>> p.is_dir() False >>> >>> p = Path('/tmp/ehh.txt') >>> p.exists() False >>> p.touch() # At last! We have `touch` in the stdlib! >>> p.exists() True
Painless read from / write to file
>>> p = Path('my_text_file') >>> p.write_text('Text file contents') # newline is NOT added automatically 18 >>> p.read_text() 'Text file contents'
More details in the official docs.
touch a file
Problem
In bash, the command “touch
” creates an empty file (with size 0). How to do this in Python?
Solution
Simply open a file in write mode and write an empty string to it.
With the stdlib:
with open("empty.txt", "w") as f: f.write("")
With the excellent unipath library:
p = Path("empty.txt") p.write_file("")
Note that this solution will overwrite your file if it exists. So be careful.