Python Forum
Use of pprint.pformat - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Use of pprint.pformat (/thread-10435.html)



Use of pprint.pformat - Truman - May-20-2018

import pprint
cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
print(pprint.pformat(cats))
fileObj = open('C:\\Python36\\kodovi\\myCats.py', 'w')
with open('myCats.py') as f:
	f.write('cats = ' + pprint.pformat(cats) + '\n')
with open('myCats.py') as f:
	print(f.read())
Error:
Traceback (most recent call last): File "C:\Python36\kodovi\pretty.py", line 6, in <module> f.write('cats = ' + pprint.pformat(cats) + '\n') io.UnsupportedOperation: not writable
example is from the same book ( Automate...), not sure why isn't it writible.


RE: Use of pprint.pformat - Larz60+ - May-20-2018

with open('myCats.py', 'w') as f:



RE: Use of pprint.pformat - snippsat - May-20-2018

You don't use fileObj,it's not needed either.
import pprint

cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
with open('cats.txt', 'w') as f:
    f.write('cats = ' + pprint.pformat(cats) + '\n')
with open('cats.txt') as f:
    print(f.read())
If you to use a path with open(r'C:\Python36\kodovi\'cats.txt', 'w') as f:
The modern way,as mention before so do not @Al Sweigart care about new stuff in Python,
like string formatting he use + everywhere and stuff like pprint.pformat() to build a string.
cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
with open('cats.txt', 'w') as f:
    f.write(f'cats = {cats}\n')
with open('cats.txt') as f:
    print(f.read())