pathlib and os.path

  |   Source

pathlib and os.path

In [5]:
!tree
.
├── example
│   └── file.txt
├── pathlib_lightning_talk.ipynb
├── pathlib_lightning_talk.slides.html
├── python_folder
│   ├── example1.py
│   ├── example2.py
│   └── example3.py
└── truth.txt

2 directories, 7 files
In [6]:
import os
from pathlib import Path
In [7]:
# the old way
os.path.realpath(os.path.curdir)
Out[7]:
'/Users/stephanfitzpatrick/git/python-weekly/week1/friday'
In [8]:
# the new way
str(Path.cwd())
Out[8]:
'/Users/stephanfitzpatrick/git/python-weekly/week1/friday'
In [9]:
# the full path to our current working directory
cwd_fullpath = os.path.realpath('.')
print(cwd_fullpath)
/Users/stephanfitzpatrick/git/python-weekly/week1/friday

iterate over paths

In [10]:
# old way
def get_paths(directory):
    """return an iterator of all paths in a given directory"""
    for root, dirs, files in os.walk(directory):
        for file in files:
            path = os.path.join(root, file)
            yield os.path.realpath(path)

list(get_paths('.'))[:5]
Out[10]:
['/Users/stephanfitzpatrick/git/python-weekly/week1/friday/.DS_Store',
 '/Users/stephanfitzpatrick/git/python-weekly/week1/friday/pathlib_lightning_talk.ipynb',
 '/Users/stephanfitzpatrick/git/python-weekly/week1/friday/pathlib_lightning_talk.slides.html',
 '/Users/stephanfitzpatrick/git/python-weekly/week1/friday/truth.txt',
 '/Users/stephanfitzpatrick/git/python-weekly/week1/friday/.ipynb_checkpoints/pathlib_lightning_talk-checkpoint.ipynb']
In [22]:
# new way
print('I was raised by wolves')
I was raised by wolves

filter paths

In [12]:
# old way
def ends_with(directory, suffix):
    """yield paths where the path ends in suffix"""
    for path in get_paths(directory):
        if path.endswith(suffix):
            yield path
            
list(ends_with('.', '.py'))
Out[12]:
['/Users/stephanfitzpatrick/git/python-weekly/week1/friday/python_folder/example1.py',
 '/Users/stephanfitzpatrick/git/python-weekly/week1/friday/python_folder/example2.py',
 '/Users/stephanfitzpatrick/git/python-weekly/week1/friday/python_folder/example3.py']
In [13]:
# new way
[path.as_posix() for path in Path.cwd().rglob('*.py')]
Out[13]:
['/Users/stephanfitzpatrick/git/python-weekly/week1/friday/python_folder/example1.py',
 '/Users/stephanfitzpatrick/git/python-weekly/week1/friday/python_folder/example2.py',
 '/Users/stephanfitzpatrick/git/python-weekly/week1/friday/python_folder/example3.py']

create paths

In [14]:
# old way
os.path.join('/', 'Users', 'stephanfitzpatrick', 'git')
Out[14]:
'/Users/stephanfitzpatrick/git'
In [15]:
# new way
str(Path('/', 'Users', 'stephanfitzpatrick', 'git'))
Out[15]:
'/Users/stephanfitzpatrick/git'

open files

In [16]:
# old way
input_path = os.path.join('.', 'truth.txt')
with open(input_path) as foo:
    print(foo.read())
Python is the shizz

In [17]:
# new way
with Path('.', 'truth.txt').open() as foo:
    print(foo.read())
Python is the shizz

variable expansion

In [18]:
# old way
os.path.expandvars("$ZSH")
Out[18]:
'/Users/stephanfitzpatrick/.oh-my-zsh'
In [19]:
# old way
os.path.expanduser("~")
Out[19]:
'/Users/stephanfitzpatrick'
In [20]:
# new way
Just kidding! The old way is still awesome :D

Once again, with feeling!

pathlib and os.path work together in beautiful harmony

In [21]:
for path in Path('.').iterdir():
    is_dir = 'is' if os.path.isdir(str(path)) else 'is not'
    print("{:34} {:<} {}".format(str(path), is_dir, 'a directory'))
.DS_Store                          is not a directory
.ipynb_checkpoints                 is a directory
example                            is a directory
pathlib_lightning_talk.ipynb       is not a directory
pathlib_lightning_talk.slides.html is not a directory
python_folder                      is a directory
truth.txt                          is not a directory
In [ ]:
 
Comments powered by Disqus