Skip to content

Instantly share code, notes, and snippets.

@limitedeternity
Last active March 14, 2023 17:52
Show Gist options
  • Save limitedeternity/38abfdae25bdfc127936ae2516c818e0 to your computer and use it in GitHub Desktop.
Save limitedeternity/38abfdae25bdfc127936ae2516c818e0 to your computer and use it in GitHub Desktop.
Functional 'zip' for text files
from argparse import ArgumentParser
from itertools import repeat
from pathlib import Path
import shutil
def main(args):
invalid_sources = filter(lambda path: not path.is_file(), args["source"])
if (source := next(invalid_sources, None)):
print("Provided source doesn't exist: %s" % source.absolute())
exit(1)
lines = []
while args["source"]:
if not args["dest"].is_file():
shutil.copy(args["source"].pop(0), args["dest"])
with args["dest"].open() as fd_dst:
while (line := fd_dst.readline().rstrip()):
lines.append(line)
if not lines:
args["dest"].unlink()
continue
break
for source in args["source"]:
longest_line = max(len(line) for line in lines)
with source.open() as fd_src:
i = 0
while (line := fd_src.readline().rstrip()):
lines[(i, i < len(lines) or lines.append(""))[0]] += "".join(repeat(" ", longest_line - len(lines[i]) + 1)) + line
i += 1
args["dest"].write_text("\n".join(lines))
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("source", type=Path, nargs="+")
parser.add_argument("--dest", type=Path, required=True)
args = parser.parse_args().__dict__
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment