Python Forum
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Use of pprint.pformat
#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


Messages In This Thread
Use of pprint.pformat - by Truman - May-20-2018, 08:50 PM
RE: Use of pprint.pformat - by Larz60+ - May-20-2018, 09:30 PM
RE: Use of pprint.pformat - by snippsat - May-20-2018, 09:32 PM

Forum Jump:

User Panel Messages

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