Python Forum
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Use of pprint.pformat
#1
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.
Reply
#2
with open('myCats.py', 'w') as f:
Reply
#3
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())
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020