Files and paths: Python snippets
Part of 30 Seconds of Python. Source: snippets/files.py.
Every example below is run as a test.
read_lines
Lines of a text file without trailing newlines.
def read_lines(path):
return Path(path).read_text(encoding='utf-8').splitlines()
>>> p = Path(tempfile.mkdtemp()) / 'a.txt'; _ = p.write_text('x\ny\n')
>>> read_lines(p)
['x', 'y']
write_atomic
Write a file so readers never see a half-written version.
def write_atomic(path, text):
path = Path(path)
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f'.{path.name}.')
try:
with os.fdopen(fd, 'w', encoding='utf-8') as f:
f.write(text)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
except BaseException:
os.unlink(tmp)
raise
>>> p = Path(tempfile.mkdtemp()) / 'cfg.json'
>>> write_atomic(p, '{}'); p.read_text()
'{}'
load_json
Read JSON, returning default if the file does not exist.
def load_json(path, default=None):
try:
return json.loads(Path(path).read_text(encoding='utf-8'))
except FileNotFoundError:
return default
>>> load_json('/no/such/file.json', default={})
{}
sha256_file
SHA-256 of a file, read in chunks so big files are fine.
def sha256_file(path, chunk_size=1 << 20):
h = hashlib.sha256()
with open(path, 'rb') as f:
while block := f.read(chunk_size):
h.update(block)
return h.hexdigest()
>>> p = Path(tempfile.mkdtemp()) / 'b.bin'; _ = p.write_bytes(b'abc')
>>> sha256_file(p)[:16]
'ba7816bf8f01cfea'
find_files
Recursively list files matching a glob, skipping noisy folders.
def find_files(root, pattern='*', exclude_dirs=('.git', 'node_modules', '__pycache__', '.venv')):
root = Path(root)
return sorted(p for p in root.rglob(pattern)
if p.is_file() and not set(p.relative_to(root).parts[:-1]) & set(exclude_dirs))
>>> d = Path(tempfile.mkdtemp()); (d / 'node_modules').mkdir(); _ = (d / 'node_modules' / 'x.py').write_text('')
>>> _ = (d / 'app.py').write_text(''); [p.name for p in find_files(d, '*.py')]
['app.py']
dir_size
Total size in bytes of every file under path.
def dir_size(path):
return sum(p.stat().st_size for p in Path(path).rglob('*') if p.is_file())
>>> d = Path(tempfile.mkdtemp()); _ = (d / 'a').write_bytes(b'12345')
>>> dir_size(d)
5
ensure_dir
Create a folder (and parents) if missing; return it as a Path.
def ensure_dir(path):
path = Path(path)
path.mkdir(parents=True, exist_ok=True)
return path
>>> d = ensure_dir(Path(tempfile.mkdtemp()) / 'a' / 'b'); d.is_dir()
True