I am trying to indent the output of pprint so that I will get an 8 space indentation with pprint. The code I used is:
import numpy as np
from pprint import pprint
A = np.array([1, 2, 3, 4])
f = open("log.txt", 'w')
n = 2
for i in range(n):
A = A + 1
f.writelines(list(u' \u27B3 - %s\n'.encode('utf-8') % i for i in A))
pprint(globals())
Output
{'A': array([2, 3, 4, 5]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 0,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}
{'A': array([3, 4, 5, 6]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 1,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}
Desired output
{'A': array([2, 3, 4, 5]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 0,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}
{'A': array([3, 4, 5, 6]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 1,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}
In short, I need a space indentation when written to file or printed with pprint
. I tried
pp = pprint.PrettyPrinter(indent=8)
but it does not work
str.join()
is a performance bottleneck. See stackoverflow.com/a/9061024 – Manzanares