WRITELOOP

PYTHON, UNICODE, STRINGS AND ZIP FILES

2017 January 3
  • How to force a unicode char escape sequence to “render” as the unicode char:

value = ‘{“name”: “Jo\u00e3o”}’ type(value) str value = unicode(value, ‘utf-8’).decode(‘unicode-escape’) u’{“name”: “João”}’

  • How to json.dump to utf-8 and make sure the string and text are both unicode:

value = ’{“name": “Jo\u00e3o”}’ type(value) str json.dumps(value, ensure_ascii=False, encoding=‘utf-8’) u’{“name”: “João”}’

  • Format strings using var names:

s3_key = ‘backups/{year}/{date_number}.zip’.format(year=lot_dt.year, date_number=lot_dt.strftime("%Y%m%d"))

  • How to format currency in python (BRL): import locale locale.setlocale(locale.LC_ALL, ‘pt_BR.utf-8’) money = float(2564500/100) locale.currency(money, grouping=True)
  • Write on a txt zipped file: with zipfile.ZipFile(zip_lot, mode=‘w’) as zf: for contract in contracts: content = ’’ fname = ‘LEN_{0}.txt’.format(contract.id) zf.writestr(fname, content)