blob: d5531029d064c2de66486b5a0db692f2fe18545b [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
Cheryl Sabella84c4b0c2018-02-25 14:06:01 -0500103way :func:`print` works: by default it 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
Andrew Kuchlingbd4e9e02017-06-13 01:31:01 -0400265It is good practice to use the :keyword:`with` keyword when dealing
266with file objects. The advantage is that the file is properly closed
267after its suite finishes, even if an exception is raised at some
268point. Using :keyword:`with` is also much shorter than writing
269equivalent :keyword:`try`\ -\ :keyword:`finally` blocks::
270
271 >>> with open('workfile') as f:
272 ... read_data = f.read()
273 >>> f.closed
274 True
275
276If you're not using the :keyword:`with` keyword, then you should call
277``f.close()`` to close the file and immediately free up any system
278resources used by it. If you don't explicitly close a file, Python's
279garbage collector will eventually destroy the object and close the
280open file for you, but the file may stay open for a while. Another
281risk is that different Python implementations will do this clean-up at
282different times.
283
284After a file object is closed, either by a :keyword:`with` statement
285or by calling ``f.close()``, attempts to use the file object will
286automatically fail. ::
287
288 >>> f.close()
289 >>> f.read()
290 Traceback (most recent call last):
291 File "<stdin>", line 1, in <module>
292 ValueError: I/O operation on closed file
293
Georg Brandl116aa622007-08-15 14:28:22 +0000294
295.. _tut-filemethods:
296
297Methods of File Objects
298-----------------------
299
300The rest of the examples in this section will assume that a file object called
301``f`` has already been created.
302
303To read a file's contents, call ``f.read(size)``, which reads some quantity of
Ezio Melotti397bb242016-01-12 11:27:30 +0200304data and returns it as a string (in text mode) or bytes object (in binary mode).
305*size* is an optional numeric argument. When *size* is omitted or negative, the
306entire contents of the file will be read and returned; it's your problem if the
307file is twice as large as your machine's memory. Otherwise, at most *size* bytes
308are read and returned.
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000309If the end of the file has been reached, ``f.read()`` will return an empty
310string (``''``). ::
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312 >>> f.read()
313 'This is the entire file.\n'
314 >>> f.read()
315 ''
316
317``f.readline()`` reads a single line from the file; a newline character (``\n``)
318is left at the end of the string, and is only omitted on the last line of the
319file if the file doesn't end in a newline. This makes the return value
320unambiguous; if ``f.readline()`` returns an empty string, the end of the file
321has been reached, while a blank line is represented by ``'\n'``, a string
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000322containing only a single newline. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000323
324 >>> f.readline()
325 'This is the first line of the file.\n'
326 >>> f.readline()
327 'Second line of the file\n'
328 >>> f.readline()
329 ''
330
Ezio Melottied3cd7e2013-04-15 19:08:31 +0300331For reading lines from a file, you can loop over the file object. This is memory
332efficient, fast, and leads to simple code::
Georg Brandl116aa622007-08-15 14:28:22 +0000333
334 >>> for line in f:
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000335 ... print(line, end='')
336 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000337 This is the first line of the file.
338 Second line of the file
339
Ezio Melottied3cd7e2013-04-15 19:08:31 +0300340If you want to read all the lines of a file in a list you can also use
341``list(f)`` or ``f.readlines()``.
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343``f.write(string)`` writes the contents of *string* to the file, returning
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000344the number of characters written. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000345
346 >>> f.write('This is a test\n')
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000347 15
Georg Brandl116aa622007-08-15 14:28:22 +0000348
Ezio Melotti397bb242016-01-12 11:27:30 +0200349Other types of objects need to be converted -- either to a string (in text mode)
350or a bytes object (in binary mode) -- before writing them::
Georg Brandl116aa622007-08-15 14:28:22 +0000351
352 >>> value = ('the answer', 42)
Ezio Melotti397bb242016-01-12 11:27:30 +0200353 >>> s = str(value) # convert the tuple to string
Georg Brandl116aa622007-08-15 14:28:22 +0000354 >>> f.write(s)
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000355 18
Georg Brandl116aa622007-08-15 14:28:22 +0000356
R David Murray1c4e4432013-07-30 15:51:57 -0400357``f.tell()`` returns an integer giving the file object's current position in the file
Georg Brandl6b4c8472014-10-30 22:26:26 +0100358represented as number of bytes from the beginning of the file when in binary mode and
359an opaque number when in text mode.
R David Murray1c4e4432013-07-30 15:51:57 -0400360
361To change the file object's position, use ``f.seek(offset, from_what)``. The position is computed
Georg Brandl116aa622007-08-15 14:28:22 +0000362from adding *offset* to a reference point; the reference point is selected by
363the *from_what* argument. A *from_what* value of 0 measures from the beginning
364of the file, 1 uses the current file position, and 2 uses the end of the file as
365the reference point. *from_what* can be omitted and defaults to 0, using the
366beginning of the file as the reference point. ::
367
Petri Lehtinen9f74c6c2013-02-23 19:26:56 +0100368 >>> f = open('workfile', 'rb+')
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000369 >>> f.write(b'0123456789abcdef')
370 16
Serhiy Storchakadba90392016-05-10 12:01:23 +0300371 >>> f.seek(5) # Go to the 6th byte in the file
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000372 5
Georg Brandl48310cd2009-01-03 21:18:54 +0000373 >>> f.read(1)
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000374 b'5'
Serhiy Storchakadba90392016-05-10 12:01:23 +0300375 >>> f.seek(-3, 2) # Go to the 3rd byte before the end
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000376 13
Georg Brandl116aa622007-08-15 14:28:22 +0000377 >>> f.read(1)
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000378 b'd'
Georg Brandl116aa622007-08-15 14:28:22 +0000379
Georg Brandl0dcb7ac2008-08-08 07:04:38 +0000380In text files (those opened without a ``b`` in the mode string), only seeks
381relative to the beginning of the file are allowed (the exception being seeking
R David Murray1c4e4432013-07-30 15:51:57 -0400382to the very file end with ``seek(0, 2)``) and the only valid *offset* values are
383those returned from the ``f.tell()``, or zero. Any other *offset* value produces
384undefined behaviour.
385
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000386File objects have some additional methods, such as :meth:`~file.isatty` and
387:meth:`~file.truncate` which are less frequently used; consult the Library
388Reference for a complete guide to file objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000389
390
Antoine Pitroudd799d22013-12-05 23:46:32 +0100391.. _tut-json:
Georg Brandl116aa622007-08-15 14:28:22 +0000392
Antoine Pitroudd799d22013-12-05 23:46:32 +0100393Saving structured data with :mod:`json`
394---------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000395
Antoine Pitroudd799d22013-12-05 23:46:32 +0100396.. index:: module: json
Georg Brandl116aa622007-08-15 14:28:22 +0000397
Antoine Pitroudd799d22013-12-05 23:46:32 +0100398Strings can easily be written to and read from a file. Numbers take a bit more
Georg Brandl116aa622007-08-15 14:28:22 +0000399effort, since the :meth:`read` method only returns strings, which will have to
400be passed to a function like :func:`int`, which takes a string like ``'123'``
Antoine Pitroudd799d22013-12-05 23:46:32 +0100401and returns its numeric value 123. When you want to save more complex data
402types like nested lists and dictionaries, parsing and serializing by hand
403becomes complicated.
Georg Brandl116aa622007-08-15 14:28:22 +0000404
Antoine Pitroudd799d22013-12-05 23:46:32 +0100405Rather than having users constantly writing and debugging code to save
406complicated data types to files, Python allows you to use the popular data
407interchange format called `JSON (JavaScript Object Notation)
408<http://json.org>`_. The standard module called :mod:`json` can take Python
409data hierarchies, and convert them to string representations; this process is
410called :dfn:`serializing`. Reconstructing the data from the string representation
411is called :dfn:`deserializing`. Between serializing and deserializing, the
412string representing the object may have been stored in a file or data, or
Georg Brandl116aa622007-08-15 14:28:22 +0000413sent over a network connection to some distant machine.
414
Antoine Pitroudd799d22013-12-05 23:46:32 +0100415.. note::
416 The JSON format is commonly used by modern applications to allow for data
417 exchange. Many programmers are already familiar with it, which makes
418 it a good choice for interoperability.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Antoine Pitroudd799d22013-12-05 23:46:32 +0100420If you have an object ``x``, you can view its JSON string representation with a
421simple line of code::
Georg Brandl116aa622007-08-15 14:28:22 +0000422
suketa1dbce042017-06-12 10:42:59 +0900423 >>> import json
Antoine Pitroudd799d22013-12-05 23:46:32 +0100424 >>> json.dumps([1, 'simple', 'list'])
425 '[1, "simple", "list"]'
Georg Brandl116aa622007-08-15 14:28:22 +0000426
Antoine Pitroudd799d22013-12-05 23:46:32 +0100427Another variant of the :func:`~json.dumps` function, called :func:`~json.dump`,
428simply serializes the object to a :term:`text file`. So if ``f`` is a
429:term:`text file` object opened for writing, we can do this::
Georg Brandl116aa622007-08-15 14:28:22 +0000430
Antoine Pitroudd799d22013-12-05 23:46:32 +0100431 json.dump(x, f)
Georg Brandl116aa622007-08-15 14:28:22 +0000432
Antoine Pitroudd799d22013-12-05 23:46:32 +0100433To decode the object again, if ``f`` is a :term:`text file` object which has
434been opened for reading::
Georg Brandl116aa622007-08-15 14:28:22 +0000435
Antoine Pitroudd799d22013-12-05 23:46:32 +0100436 x = json.load(f)
437
438This simple serialization technique can handle lists and dictionaries, but
439serializing arbitrary class instances in JSON requires a bit of extra effort.
440The reference for the :mod:`json` module contains an explanation of this.
441
442.. seealso::
443
444 :mod:`pickle` - the pickle module
445
446 Contrary to :ref:`JSON <tut-json>`, *pickle* is a protocol which allows
447 the serialization of arbitrarily complex Python objects. As such, it is
448 specific to Python and cannot be used to communicate with applications
449 written in other languages. It is also insecure by default:
450 deserializing pickle data coming from an untrusted source can execute
451 arbitrary code, if the data was crafted by a skilled attacker.