blob: beeaac36b9bd24b73ad24c93f2717b458d986334 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _tut-io:
2
3****************
4Input and Output
5****************
6
7There are several ways to present the output of a program; data can be printed
8in a human-readable form, or written to a file for future use. This chapter will
9discuss some of the possibilities.
10
11
12.. _tut-formatting:
13
14Fancier Output Formatting
15=========================
16
17So far we've encountered two ways of writing values: *expression statements* and
Guido van Rossum0616b792007-08-31 03:25:11 +000018the :func:`print` function. (A third way is using the :meth:`write` method
Georg Brandl116aa622007-08-15 14:28:22 +000019of file objects; the standard output file can be referenced as ``sys.stdout``.
20See the Library Reference for more information on this.)
21
Georg Brandl116aa622007-08-15 14:28:22 +000022Often you'll want more control over the formatting of your output than simply
23printing space-separated values. There are two ways to format your output; the
24first way is to do all the string handling yourself; using string slicing and
25concatenation operations you can create any layout you can imagine. The
Georg Brandl3640e182011-03-06 10:56:18 +010026string type has some methods that perform useful operations for padding
Georg Brandl116aa622007-08-15 14:28:22 +000027strings to a given column width; these will be discussed shortly. The second
Martin Panterbc1ee462016-02-13 00:41:37 +000028way is to use :ref:`formatted string literals <f-strings>`, or the
29:meth:`str.format` method.
Benjamin Petersone6f00632008-05-26 01:03:56 +000030
Georg Brandl3640e182011-03-06 10:56:18 +010031The :mod:`string` module contains a :class:`~string.Template` class which offers
32yet another way to substitute values into strings.
Georg Brandl116aa622007-08-15 14:28:22 +000033
34One question remains, of course: how do you convert values to strings? Luckily,
35Python has ways to convert any value to a string: pass it to the :func:`repr`
Georg Brandl1e3830a2008-08-08 06:45:01 +000036or :func:`str` functions.
Georg Brandl116aa622007-08-15 14:28:22 +000037
38The :func:`str` function is meant to return representations of values which are
39fairly human-readable, while :func:`repr` is meant to generate representations
40which can be read by the interpreter (or will force a :exc:`SyntaxError` if
Sandro Tosia17ef142012-08-14 19:51:43 +020041there is no equivalent syntax). For objects which don't have a particular
Georg Brandl116aa622007-08-15 14:28:22 +000042representation for human consumption, :func:`str` will return the same value as
43:func:`repr`. Many values, such as numbers or structures like lists and
Ezio Melotti0def5c62011-03-13 02:27:26 +020044dictionaries, have the same representation using either function. Strings, in
45particular, have two distinct representations.
Georg Brandl116aa622007-08-15 14:28:22 +000046
47Some examples::
48
49 >>> s = 'Hello, world.'
50 >>> str(s)
51 'Hello, world.'
52 >>> repr(s)
53 "'Hello, world.'"
Ezio Melotti0def5c62011-03-13 02:27:26 +020054 >>> str(1/7)
Mark Dickinson5a55b612009-06-28 20:59:42 +000055 '0.14285714285714285'
Georg Brandl116aa622007-08-15 14:28:22 +000056 >>> x = 10 * 3.25
57 >>> y = 200 * 200
58 >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
Guido van Rossum0616b792007-08-31 03:25:11 +000059 >>> print(s)
Georg Brandl116aa622007-08-15 14:28:22 +000060 The value of x is 32.5, and y is 40000...
61 >>> # The repr() of a string adds string quotes and backslashes:
62 ... hello = 'hello, world\n'
63 >>> hellos = repr(hello)
Guido van Rossum0616b792007-08-31 03:25:11 +000064 >>> print(hellos)
Georg Brandl116aa622007-08-15 14:28:22 +000065 'hello, world\n'
66 >>> # The argument to repr() may be any Python object:
67 ... repr((x, y, ('spam', 'eggs')))
68 "(32.5, 40000, ('spam', 'eggs'))"
Georg Brandl116aa622007-08-15 14:28:22 +000069
70Here are two ways to write a table of squares and cubes::
71
72 >>> for x in range(1, 11):
Georg Brandle4ac7502007-09-03 07:10:24 +000073 ... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +000074 ... # Note use of 'end' on previous line
75 ... print(repr(x*x*x).rjust(4))
Georg Brandl116aa622007-08-15 14:28:22 +000076 ...
77 1 1 1
78 2 4 8
79 3 9 27
80 4 16 64
81 5 25 125
82 6 36 216
83 7 49 343
84 8 64 512
85 9 81 729
86 10 100 1000
87
Georg Brandle4ac7502007-09-03 07:10:24 +000088 >>> for x in range(1, 11):
Benjamin Petersone6f00632008-05-26 01:03:56 +000089 ... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
Georg Brandl48310cd2009-01-03 21:18:54 +000090 ...
Georg Brandl116aa622007-08-15 14:28:22 +000091 1 1 1
92 2 4 8
93 3 9 27
94 4 16 64
95 5 25 125
96 6 36 216
97 7 49 343
98 8 64 512
99 9 81 729
100 10 100 1000
101
102(Note that in the first example, one space between each column was added by the
Guido van Rossum0616b792007-08-31 03:25:11 +0000103way :func:`print` works: it always adds spaces between its arguments.)
Georg Brandl116aa622007-08-15 14:28:22 +0000104
Ezio Melotti2b736602011-03-13 02:19:57 +0200105This example demonstrates the :meth:`str.rjust` method of string
106objects, which right-justifies a string in a field of a given width by padding
107it with spaces on the left. There are similar methods :meth:`str.ljust` and
108:meth:`str.center`. These methods do not write anything, they just return a
109new string. If the input string is too long, they don't truncate it, but
110return it unchanged; this will mess up your column lay-out but that's usually
111better than the alternative, which would be lying about a value. (If you
112really want truncation you can always add a slice operation, as in
113``x.ljust(n)[:n]``.)
Georg Brandl116aa622007-08-15 14:28:22 +0000114
Ezio Melotti2b736602011-03-13 02:19:57 +0200115There is another method, :meth:`str.zfill`, which pads a numeric string on the
116left with zeros. It understands about plus and minus signs::
Georg Brandl116aa622007-08-15 14:28:22 +0000117
118 >>> '12'.zfill(5)
119 '00012'
120 >>> '-3.14'.zfill(7)
121 '-003.14'
122 >>> '3.14159265359'.zfill(5)
123 '3.14159265359'
124
Benjamin Petersone6f00632008-05-26 01:03:56 +0000125Basic usage of the :meth:`str.format` method looks like this::
126
Georg Brandl2f3ed682009-09-01 07:42:40 +0000127 >>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
Benjamin Petersone6f00632008-05-26 01:03:56 +0000128 We are the knights who say "Ni!"
129
130The brackets and characters within them (called format fields) are replaced with
Ezio Melotti2b736602011-03-13 02:19:57 +0200131the objects passed into the :meth:`str.format` method. A number in the
Georg Brandl2f3ed682009-09-01 07:42:40 +0000132brackets can be used to refer to the position of the object passed into the
Ezio Melotti2b736602011-03-13 02:19:57 +0200133:meth:`str.format` method. ::
Benjamin Petersone6f00632008-05-26 01:03:56 +0000134
Benjamin Peterson0cea1572008-07-26 21:59:03 +0000135 >>> print('{0} and {1}'.format('spam', 'eggs'))
Benjamin Petersone6f00632008-05-26 01:03:56 +0000136 spam and eggs
Benjamin Peterson0cea1572008-07-26 21:59:03 +0000137 >>> print('{1} and {0}'.format('spam', 'eggs'))
Benjamin Petersone6f00632008-05-26 01:03:56 +0000138 eggs and spam
139
Ezio Melotti2b736602011-03-13 02:19:57 +0200140If keyword arguments are used in the :meth:`str.format` method, their values
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000141are referred to by using the name of the argument. ::
Benjamin Petersone6f00632008-05-26 01:03:56 +0000142
Benjamin Peterson71141932008-07-26 22:27:04 +0000143 >>> print('This {food} is {adjective}.'.format(
144 ... food='spam', adjective='absolutely horrible'))
Benjamin Petersone6f00632008-05-26 01:03:56 +0000145 This spam is absolutely horrible.
146
147Positional and keyword arguments can be arbitrarily combined::
148
Benjamin Peterson71141932008-07-26 22:27:04 +0000149 >>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
150 other='Georg'))
Benjamin Petersone6f00632008-05-26 01:03:56 +0000151 The story of Bill, Manfred, and Georg.
152
Georg Brandl2f3ed682009-09-01 07:42:40 +0000153``'!a'`` (apply :func:`ascii`), ``'!s'`` (apply :func:`str`) and ``'!r'``
154(apply :func:`repr`) can be used to convert the value before it is formatted::
155
Georg Brandlf1d371b2016-02-22 14:52:55 +0100156 >>> contents = 'eels'
157 >>> print('My hovercraft is full of {}.'.format(contents))
158 My hovercraft is full of eels.
159 >>> print('My hovercraft is full of {!r}.'.format(contents))
160 My hovercraft is full of 'eels'.
Georg Brandl2f3ed682009-09-01 07:42:40 +0000161
Alexandre Vassalottie223eb82009-07-29 20:12:15 +0000162An optional ``':'`` and format specifier can follow the field name. This allows
Benjamin Petersone6f00632008-05-26 01:03:56 +0000163greater control over how the value is formatted. The following example
Raymond Hettinger756fe262011-02-24 00:06:16 +0000164rounds Pi to three places after the decimal.
Georg Brandl116aa622007-08-15 14:28:22 +0000165
166 >>> import math
Benjamin Petersone6f00632008-05-26 01:03:56 +0000167 >>> print('The value of PI is approximately {0:.3f}.'.format(math.pi))
Georg Brandl116aa622007-08-15 14:28:22 +0000168 The value of PI is approximately 3.142.
169
Benjamin Petersone6f00632008-05-26 01:03:56 +0000170Passing an integer after the ``':'`` will cause that field to be a minimum
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000171number of characters wide. This is useful for making tables pretty. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000172
173 >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
174 >>> for name, phone in table.items():
Benjamin Petersone6f00632008-05-26 01:03:56 +0000175 ... print('{0:10} ==> {1:10d}'.format(name, phone))
Georg Brandl48310cd2009-01-03 21:18:54 +0000176 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000177 Jack ==> 4098
178 Dcab ==> 7678
179 Sjoerd ==> 4127
180
Georg Brandl116aa622007-08-15 14:28:22 +0000181If you have a really long format string that you don't want to split up, it
182would be nice if you could reference the variables to be formatted by name
Benjamin Petersone6f00632008-05-26 01:03:56 +0000183instead of by position. This can be done by simply passing the dict and using
184square brackets ``'[]'`` to access the keys ::
Georg Brandl116aa622007-08-15 14:28:22 +0000185
186 >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
Benjamin Peterson71141932008-07-26 22:27:04 +0000187 >>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
Andrew Svetlove9cf97c2012-10-17 16:41:28 +0300188 ... 'Dcab: {0[Dcab]:d}'.format(table))
Benjamin Petersone6f00632008-05-26 01:03:56 +0000189 Jack: 4098; Sjoerd: 4127; Dcab: 8637678
190
191This could also be done by passing the table as keyword arguments with the '**'
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000192notation. ::
Benjamin Petersone6f00632008-05-26 01:03:56 +0000193
194 >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
195 >>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Georg Brandl116aa622007-08-15 14:28:22 +0000196 Jack: 4098; Sjoerd: 4127; Dcab: 8637678
197
Ezio Melotti2b736602011-03-13 02:19:57 +0200198This is particularly useful in combination with the built-in function
199:func:`vars`, which returns a dictionary containing all local variables.
Georg Brandl116aa622007-08-15 14:28:22 +0000200
Mark Dickinson934896d2009-02-21 20:59:32 +0000201For a complete overview of string formatting with :meth:`str.format`, see
Benjamin Petersone6f00632008-05-26 01:03:56 +0000202:ref:`formatstrings`.
203
204
205Old string formatting
206---------------------
207
208The ``%`` operator can also be used for string formatting. It interprets the
Georg Brandl60203b42010-10-06 10:11:56 +0000209left argument much like a :c:func:`sprintf`\ -style format string to be applied
Benjamin Petersone6f00632008-05-26 01:03:56 +0000210to the right argument, and returns the string resulting from this formatting
211operation. For example::
212
213 >>> import math
Georg Brandl11e18b02008-08-05 09:04:16 +0000214 >>> print('The value of PI is approximately %5.3f.' % math.pi)
Benjamin Petersone6f00632008-05-26 01:03:56 +0000215 The value of PI is approximately 3.142.
216
Benjamin Petersone6f00632008-05-26 01:03:56 +0000217More information can be found in the :ref:`old-string-formatting` section.
218
Georg Brandl116aa622007-08-15 14:28:22 +0000219
220.. _tut-files:
221
222Reading and Writing Files
223=========================
224
225.. index::
226 builtin: open
227 object: file
228
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000229:func:`open` returns a :term:`file object`, and is most commonly used with
230two arguments: ``open(filename, mode)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000231
Georg Brandl116aa622007-08-15 14:28:22 +0000232::
233
Petri Lehtinen9f74c6c2013-02-23 19:26:56 +0100234 >>> f = open('workfile', 'w')
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000235
236.. XXX str(f) is <io.TextIOWrapper object at 0x82e8dc4>
237
Guido van Rossum0616b792007-08-31 03:25:11 +0000238 >>> print(f)
Petri Lehtinen9f74c6c2013-02-23 19:26:56 +0100239 <open file 'workfile', mode 'w' at 80a0960>
Georg Brandl116aa622007-08-15 14:28:22 +0000240
241The first argument is a string containing the filename. The second argument is
242another string containing a few characters describing the way in which the file
243will be used. *mode* can be ``'r'`` when the file will only be read, ``'w'``
244for only writing (an existing file with the same name will be erased), and
245``'a'`` opens the file for appending; any data written to the file is
246automatically added to the end. ``'r+'`` opens the file for both reading and
247writing. The *mode* argument is optional; ``'r'`` will be assumed if it's
248omitted.
249
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000250Normally, files are opened in :dfn:`text mode`, that means, you read and write
Alessandro Cuccid8de44b2015-07-28 21:00:10 +0200251strings from and to the file, which are encoded in a specific encoding. If
Jason R. Coombs842c0742015-07-29 14:04:36 -0400252encoding is not specified, the default is platform dependent (see
253:func:`open`). ``'b'`` appended to the mode opens the file in
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000254:dfn:`binary mode`: now the data is read and written in the form of bytes
255objects. This mode should be used for all files that don't contain text.
Skip Montanaro4e02c502007-09-26 01:10:12 +0000256
Chris Jerdonek5bf7f1f2012-10-17 20:17:41 -0700257In text mode, the default when reading is to convert platform-specific line
258endings (``\n`` on Unix, ``\r\n`` on Windows) to just ``\n``. When writing in
259text mode, the default is to convert occurrences of ``\n`` back to
260platform-specific line endings. This behind-the-scenes modification
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000261to file data is fine for text files, but will corrupt binary data like that in
262:file:`JPEG` or :file:`EXE` files. Be very careful to use binary mode when
263reading and writing such files.
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265
266.. _tut-filemethods:
267
268Methods of File Objects
269-----------------------
270
271The rest of the examples in this section will assume that a file object called
272``f`` has already been created.
273
274To read a file's contents, call ``f.read(size)``, which reads some quantity of
Ezio Melotti397bb242016-01-12 11:27:30 +0200275data and returns it as a string (in text mode) or bytes object (in binary mode).
276*size* is an optional numeric argument. When *size* is omitted or negative, the
277entire contents of the file will be read and returned; it's your problem if the
278file is twice as large as your machine's memory. Otherwise, at most *size* bytes
279are read and returned.
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000280If the end of the file has been reached, ``f.read()`` will return an empty
281string (``''``). ::
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283 >>> f.read()
284 'This is the entire file.\n'
285 >>> f.read()
286 ''
287
288``f.readline()`` reads a single line from the file; a newline character (``\n``)
289is left at the end of the string, and is only omitted on the last line of the
290file if the file doesn't end in a newline. This makes the return value
291unambiguous; if ``f.readline()`` returns an empty string, the end of the file
292has been reached, while a blank line is represented by ``'\n'``, a string
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000293containing only a single newline. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000294
295 >>> f.readline()
296 'This is the first line of the file.\n'
297 >>> f.readline()
298 'Second line of the file\n'
299 >>> f.readline()
300 ''
301
Ezio Melottied3cd7e2013-04-15 19:08:31 +0300302For reading lines from a file, you can loop over the file object. This is memory
303efficient, fast, and leads to simple code::
Georg Brandl116aa622007-08-15 14:28:22 +0000304
305 >>> for line in f:
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000306 ... print(line, end='')
307 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000308 This is the first line of the file.
309 Second line of the file
310
Ezio Melottied3cd7e2013-04-15 19:08:31 +0300311If you want to read all the lines of a file in a list you can also use
312``list(f)`` or ``f.readlines()``.
Georg Brandl116aa622007-08-15 14:28:22 +0000313
314``f.write(string)`` writes the contents of *string* to the file, returning
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000315the number of characters written. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000316
317 >>> f.write('This is a test\n')
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000318 15
Georg Brandl116aa622007-08-15 14:28:22 +0000319
Ezio Melotti397bb242016-01-12 11:27:30 +0200320Other types of objects need to be converted -- either to a string (in text mode)
321or a bytes object (in binary mode) -- before writing them::
Georg Brandl116aa622007-08-15 14:28:22 +0000322
323 >>> value = ('the answer', 42)
Ezio Melotti397bb242016-01-12 11:27:30 +0200324 >>> s = str(value) # convert the tuple to string
Georg Brandl116aa622007-08-15 14:28:22 +0000325 >>> f.write(s)
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000326 18
Georg Brandl116aa622007-08-15 14:28:22 +0000327
R David Murray1c4e4432013-07-30 15:51:57 -0400328``f.tell()`` returns an integer giving the file object's current position in the file
Georg Brandl6b4c8472014-10-30 22:26:26 +0100329represented as number of bytes from the beginning of the file when in binary mode and
330an opaque number when in text mode.
R David Murray1c4e4432013-07-30 15:51:57 -0400331
332To change the file object's position, use ``f.seek(offset, from_what)``. The position is computed
Georg Brandl116aa622007-08-15 14:28:22 +0000333from adding *offset* to a reference point; the reference point is selected by
334the *from_what* argument. A *from_what* value of 0 measures from the beginning
335of the file, 1 uses the current file position, and 2 uses the end of the file as
336the reference point. *from_what* can be omitted and defaults to 0, using the
337beginning of the file as the reference point. ::
338
Petri Lehtinen9f74c6c2013-02-23 19:26:56 +0100339 >>> f = open('workfile', 'rb+')
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000340 >>> f.write(b'0123456789abcdef')
341 16
Serhiy Storchakadba90392016-05-10 12:01:23 +0300342 >>> f.seek(5) # Go to the 6th byte in the file
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000343 5
Georg Brandl48310cd2009-01-03 21:18:54 +0000344 >>> f.read(1)
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000345 b'5'
Serhiy Storchakadba90392016-05-10 12:01:23 +0300346 >>> f.seek(-3, 2) # Go to the 3rd byte before the end
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000347 13
Georg Brandl116aa622007-08-15 14:28:22 +0000348 >>> f.read(1)
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000349 b'd'
Georg Brandl116aa622007-08-15 14:28:22 +0000350
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000351In text files (those opened without a ``b`` in the mode string), only seeks
352relative to the beginning of the file are allowed (the exception being seeking
R David Murray1c4e4432013-07-30 15:51:57 -0400353to the very file end with ``seek(0, 2)``) and the only valid *offset* values are
354those returned from the ``f.tell()``, or zero. Any other *offset* value produces
355undefined behaviour.
356
Georg Brandl48310cd2009-01-03 21:18:54 +0000357
Georg Brandl116aa622007-08-15 14:28:22 +0000358When you're done with a file, call ``f.close()`` to close it and free up any
359system resources taken up by the open file. After calling ``f.close()``,
360attempts to use the file object will automatically fail. ::
361
362 >>> f.close()
363 >>> f.read()
364 Traceback (most recent call last):
365 File "<stdin>", line 1, in ?
366 ValueError: I/O operation on closed file
367
Georg Brandl3dbca812008-07-23 16:10:53 +0000368It is good practice to use the :keyword:`with` keyword when dealing with file
369objects. This has the advantage that the file is properly closed after its
370suite finishes, even if an exception is raised on the way. It is also much
371shorter than writing equivalent :keyword:`try`\ -\ :keyword:`finally` blocks::
372
Petri Lehtinen9f74c6c2013-02-23 19:26:56 +0100373 >>> with open('workfile', 'r') as f:
Georg Brandl3dbca812008-07-23 16:10:53 +0000374 ... read_data = f.read()
375 >>> f.closed
376 True
377
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000378File objects have some additional methods, such as :meth:`~file.isatty` and
379:meth:`~file.truncate` which are less frequently used; consult the Library
380Reference for a complete guide to file objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000381
382
Antoine Pitroudd799d22013-12-05 23:46:32 +0100383.. _tut-json:
Georg Brandl116aa622007-08-15 14:28:22 +0000384
Antoine Pitroudd799d22013-12-05 23:46:32 +0100385Saving structured data with :mod:`json`
386---------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000387
Antoine Pitroudd799d22013-12-05 23:46:32 +0100388.. index:: module: json
Georg Brandl116aa622007-08-15 14:28:22 +0000389
Antoine Pitroudd799d22013-12-05 23:46:32 +0100390Strings can easily be written to and read from a file. Numbers take a bit more
Georg Brandl116aa622007-08-15 14:28:22 +0000391effort, since the :meth:`read` method only returns strings, which will have to
392be passed to a function like :func:`int`, which takes a string like ``'123'``
Antoine Pitroudd799d22013-12-05 23:46:32 +0100393and returns its numeric value 123. When you want to save more complex data
394types like nested lists and dictionaries, parsing and serializing by hand
395becomes complicated.
Georg Brandl116aa622007-08-15 14:28:22 +0000396
Antoine Pitroudd799d22013-12-05 23:46:32 +0100397Rather than having users constantly writing and debugging code to save
398complicated data types to files, Python allows you to use the popular data
399interchange format called `JSON (JavaScript Object Notation)
400<http://json.org>`_. The standard module called :mod:`json` can take Python
401data hierarchies, and convert them to string representations; this process is
402called :dfn:`serializing`. Reconstructing the data from the string representation
403is called :dfn:`deserializing`. Between serializing and deserializing, the
404string representing the object may have been stored in a file or data, or
Georg Brandl116aa622007-08-15 14:28:22 +0000405sent over a network connection to some distant machine.
406
Antoine Pitroudd799d22013-12-05 23:46:32 +0100407.. note::
408 The JSON format is commonly used by modern applications to allow for data
409 exchange. Many programmers are already familiar with it, which makes
410 it a good choice for interoperability.
Georg Brandl116aa622007-08-15 14:28:22 +0000411
Antoine Pitroudd799d22013-12-05 23:46:32 +0100412If you have an object ``x``, you can view its JSON string representation with a
413simple line of code::
Georg Brandl116aa622007-08-15 14:28:22 +0000414
Antoine Pitroudd799d22013-12-05 23:46:32 +0100415 >>> json.dumps([1, 'simple', 'list'])
416 '[1, "simple", "list"]'
Georg Brandl116aa622007-08-15 14:28:22 +0000417
Antoine Pitroudd799d22013-12-05 23:46:32 +0100418Another variant of the :func:`~json.dumps` function, called :func:`~json.dump`,
419simply serializes the object to a :term:`text file`. So if ``f`` is a
420:term:`text file` object opened for writing, we can do this::
Georg Brandl116aa622007-08-15 14:28:22 +0000421
Antoine Pitroudd799d22013-12-05 23:46:32 +0100422 json.dump(x, f)
Georg Brandl116aa622007-08-15 14:28:22 +0000423
Antoine Pitroudd799d22013-12-05 23:46:32 +0100424To decode the object again, if ``f`` is a :term:`text file` object which has
425been opened for reading::
Georg Brandl116aa622007-08-15 14:28:22 +0000426
Antoine Pitroudd799d22013-12-05 23:46:32 +0100427 x = json.load(f)
428
429This simple serialization technique can handle lists and dictionaries, but
430serializing arbitrary class instances in JSON requires a bit of extra effort.
431The reference for the :mod:`json` module contains an explanation of this.
432
433.. seealso::
434
435 :mod:`pickle` - the pickle module
436
437 Contrary to :ref:`JSON <tut-json>`, *pickle* is a protocol which allows
438 the serialization of arbitrarily complex Python objects. As such, it is
439 specific to Python and cannot be used to communicate with applications
440 written in other languages. It is also insecure by default:
441 deserializing pickle data coming from an untrusted source can execute
442 arbitrary code, if the data was crafted by a skilled attacker.