56 lines
973 B
Python
56 lines
973 B
Python
#! /usr/bin/env python3
|
|
# encoding: utf-8
|
|
|
|
from contextlib import contextmanager
|
|
import os
|
|
|
|
# --------------------------------------------------
|
|
|
|
def touch(path, times=None):
|
|
"""
|
|
Sets a `path`'s atime and mtime.
|
|
|
|
`times` is a tuple of (atime, mtime) and defaults to "now".
|
|
|
|
@while touching a file
|
|
"""
|
|
|
|
path = os.path.expanduser(path)
|
|
|
|
with open(path, "a"):
|
|
os.utime(path, times)
|
|
|
|
# --------------------------------------------------
|
|
|
|
def count_lines(path):
|
|
"""
|
|
A reasonably fast and memory-lean line counter.
|
|
|
|
@while counting lines in a file
|
|
"""
|
|
|
|
lines = 0
|
|
buffer = bytearray(int(2**20))
|
|
path = os.path.expanduser(path)
|
|
|
|
with open(path, "rb") as f:
|
|
while f.readinto(buffer):
|
|
lines += buffer.count(b"\n")
|
|
|
|
return lines
|
|
|
|
# --------------------------------------------------
|
|
|
|
@contextmanager
|
|
def context_dir(path):
|
|
"""
|
|
A directory context manager.
|
|
"""
|
|
|
|
previous = os.getcwd()
|
|
os.chdir(path)
|
|
|
|
try:
|
|
yield
|
|
finally:
|
|
os.chdir(previous)
|