move all text files to an archive directory
import glob
import os
import shutil
for file_name in glob.glob('*.txt'):
new_path = os.path.join('archive', file_name)
shutil.move(file_name, new_path)
.cwd()
(Current Working Directory) and .home()
(your user’s home directory)
import pathlib
pathlib.Path.cwd()
pathlib.Path.home()
Creating Paths
pathlib.Path(r'C:\Users\gahjelle\realpython\file.txt')
or
pathlib.Path.home() / 'python' / 'scripts' / 'test.py'
or
pathlib.Path.home().joinpath('python', 'scripts', 'test.py')
finds all headers in a Markdown file and prints them
path = pathlib.Path.cwd() / 'test.md'
with open(path, mode='r') as fid:
headers = [line.strip() for line in fid if line.startswith('#')]
print('\n'.join(headers))
or
path = pathlib.Path.cwd() / 'test.md'
with path.open(mode='r') as fid:
headers = [line.strip() for line in fid if line.startswith('#')]
print('\n'.join(headers))
properties
path = pathlib.Path('test.md')
path.resolve()
path
# PosixPath('/home/gahjelle/realpython/test.md')
path.name
# 'test.md'
path.stem
# 'test'
path.suffix
# '.md'
path.parent
# PosixPath('/home/gahjelle/realpython')
path.parent.parent
# PosixPath('/home/gahjelle')
path.anchor
#'/'
path.parent.parent / ('new' + path.suffix)
# PosixPath('/home/gahjelle/new.md')
count how many files there are of each filetype in the current directory
import collections
collections.Counter(p.suffix for p in pathlib.Path.cwd().iterdir())
#Counter({'.md': 2, '.txt': 4, '.pdf': 2, '.py': 1})
only counts filetypes starting with p
import collections
collections.Counter(p.suffix for p in pathlib.Path.cwd().glob('*.p*'))
#Counter({'.pdf': 2, '.py': 1})
Display a Directory Tree
def tree(directory):
print(f'+ {directory}')
for path in sorted(directory.rglob('*')):
depth = len(path.relative_to(directory).parts)
spacer = ' ' * depth
print(f'{spacer}+ {path.name}')
tree(pathlib.Path.cwd())
#+ /home/gahjelle/realpython
# + directory_1
#+ file_a.md
#+ directory_2
# + file_a.md
#+ file_b.pdf
# + file_c.py
# + file_1.txt
# + file_2.txt
Create a Unique File Name
def unique_path(directory, name_pattern):
counter = 0
while True:
counter += 1
path = directory / name_pattern.format(counter)
if not path.exists():
return path
path = unique_path(pathlib.Path.cwd(), 'test{:03d}.txt')