pathlib and os.path
pathlib and os.path¶
navigate folders like a pro!¶
In [5]:
!tree
In [6]:
import os
from pathlib import Path
print the current working directory¶
In [7]:
# the old way
os.path.realpath(os.path.curdir)
Out[7]:
In [8]:
# the new way
str(Path.cwd())
Out[8]:
In [9]:
# the full path to our current working directory
cwd_fullpath = os.path.realpath('.')
print(cwd_fullpath)
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]:
In [22]:
# new way
print('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]:
In [13]:
# new way
[path.as_posix() for path in Path.cwd().rglob('*.py')]
Out[13]:
create paths¶
In [14]:
# old way
os.path.join('/', 'Users', 'stephanfitzpatrick', 'git')
Out[14]:
In [15]:
# new way
str(Path('/', 'Users', 'stephanfitzpatrick', 'git'))
Out[15]:
open files¶
In [16]:
# old way
input_path = os.path.join('.', 'truth.txt')
with open(input_path) as foo:
print(foo.read())
In [17]:
# new way
with Path('.', 'truth.txt').open() as foo:
print(foo.read())
variable expansion¶
In [18]:
# old way
os.path.expandvars("$ZSH")
Out[18]:
In [19]:
# old way
os.path.expanduser("~")
Out[19]:
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'))
In [ ]: