0% found this document useful (0 votes)
18 views

Python Pages Doc Ic Ac Uk CPP Lessons CPP 10 Files 04 Dump HTML

This document is a chapter from a book about Python programming for C++ programmers. It discusses writing Python objects to JSON files. Specifically, it explains that the json.dump() method can be used to serialize a Python data object into a JSON string and save it to a file. An example is provided where a Python dictionary is serialized and written to an output.json file using json.dump(). It also mentions that json.dumps() can be used to serialize the data to a JSON string without writing it to a file.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Python Pages Doc Ic Ac Uk CPP Lessons CPP 10 Files 04 Dump HTML

This document is a chapter from a book about Python programming for C++ programmers. It discusses writing Python objects to JSON files. Specifically, it explains that the json.dump() method can be used to serialize a Python data object into a JSON string and save it to a file. An example is provided where a Python dictionary is serialized and written to an output.json file using json.dump(). It also mentions that json.dumps() can be used to serialize the data to a JSON string without writing it to a file.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python Programming home

Department of Computing, Imperial College London

Python for C++ Programmers


Chapter 1: Introduction
Chapter 2: Basic data types
Chapter 3: Variables and operators
Chapter 4: Sequence types
Chapter 5: Sets and dictionaries
Chapter 6: Control flow
Chapter 7: Functions
Chapter 8: Object-oriented programming
Chapter 9: Modules
Chapter 10: Files
[10.1] Handling text files
[10.2] JSON files
[10.3] Loading JSON files
[10.4] Writing to JSON files
[10.5] pickle
[10.6] Pickling time!
[10.7] CSV files
[10.8] Reading CSV files
[10.9] Reading CSV files into a dict
[10.10] Writing to CSV files
[10.11] That's a wrap!

Chapter 10: Files


>> Writing to JSON files
face Josiah Wang

Conversely, you can also easily write a Python object to a JSON string. The fancy term is serialisation
(converting a data object into a string representation, usually for storage or transmission).
To write your data into a JSON file, use json.dump(). The following code serialises data to JSON format and saves it
in a file called output.json.

import json

data = {"course": "Introduction to Machine Learning", "term": 1}

with open("output.json", "w") as jsonfile:


json.dump(data, jsonfile)

To write your data to a string (and do something else with it later), use json.dumps().

json_string = json.dumps(data)
print(json_string) # {"course": "Introduction to Machine Learning", "term": 1}
Previous Next 

Page designed by Josiah Wang Department of Computing | Imperial College London

You might also like