User:OrphicBot/utils.py

# small utility functions for reuse

def flatten(ll) : return [x for l in ll for x in l] 

import os

def readFile(path) : 
  file = open(path, encoding = 'utf-8')
  x = file.read()
  file.close()
  return x

def tuplesToFileDelim(ts, path, delim) :
  txt = ""
  for t in ts :
    L = len(t)
    for r in range(0, L) :
      txt += str(t[r])
      txt += delim if r < L-1 else '\n'
  file = open(path, "w+", encoding = 'utf-8')
  file.write(txt)
  file.close()

def tuplesToFile(ts, path) : return tuplesToFileDelim(ts, path, ',')

def fileToTuplesDelim(path, delim) :
  file = open(path, encoding = 'utf-8')
  ts = list(map(lambda x: tuple(x.split(delim)), file.read().strip().split('\n')))
  file.close()
  return ts

def txtToFile(t,f) :
  file = open(f, "w+", encoding = 'utf-8')
  file.write(t)
  file.close()

from subprocess import call
import threading
import random

def show(x) :
  def pdel(f) :
    call("notepad {}".format(f))
    os.remove(f)
  fn = "fakeClipboard{}.txt".format(random.randint(0,1000000))
  txtToFile(x, fn)
  threading.Thread(target = pdel, args=(fn,) ).start()

def appose(x,y) :
  xs, ys = x.split('\n'), y.split('\n')
  xMax = max([len(l) for l in xs])+2
  lMax = max(len(xs), len(ys))
  return "\n".join((xs[l] if l < len(xs) else "") + (' '*(xMax - (len(xs[l]) if l < len(xs) else 0)  )) + (ys[l] if l < len(ys) else "") for l in range(0,lMax))+'\n'
  
def showTwo(x,y) :
  def pdel(f) :
    call("notepad {}".format(f))
    os.remove(f)
  fn = "fakeClipboard{}.txt".format(random.randint(0,1000000))
  txtToFile(append(x,y), fn)
  threading.Thread(target = pdel, args=(fn,) ).start()