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.
with open('myCats.py', 'w') as f:
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())