Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | .. _tut-io: |
| 2 | |
| 3 | **************** |
| 4 | Input and Output |
| 5 | **************** |
| 6 | |
| 7 | There are several ways to present the output of a program; data can be printed |
| 8 | in a human-readable form, or written to a file for future use. This chapter will |
| 9 | discuss some of the possibilities. |
| 10 | |
| 11 | |
| 12 | .. _tut-formatting: |
| 13 | |
| 14 | Fancier Output Formatting |
| 15 | ========================= |
| 16 | |
| 17 | So far we've encountered two ways of writing values: *expression statements* and |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 18 | the :func:`print` function. (A third way is using the :meth:`write` method |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 19 | of file objects; the standard output file can be referenced as ``sys.stdout``. |
| 20 | See the Library Reference for more information on this.) |
| 21 | |
| 22 | .. index:: module: string |
| 23 | |
| 24 | Often you'll want more control over the formatting of your output than simply |
| 25 | printing space-separated values. There are two ways to format your output; the |
| 26 | first way is to do all the string handling yourself; using string slicing and |
| 27 | concatenation operations you can create any layout you can imagine. The |
| 28 | standard module :mod:`string` contains some useful operations for padding |
| 29 | strings to a given column width; these will be discussed shortly. The second |
Benjamin Peterson | e6f0063 | 2008-05-26 01:03:56 +0000 | [diff] [blame] | 30 | way is to use the :meth:`str.format` method. |
| 31 | |
| 32 | The :mod:`string` module contains a class Template which offers yet another way |
| 33 | to substitute values into strings. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 34 | |
| 35 | One question remains, of course: how do you convert values to strings? Luckily, |
| 36 | Python has ways to convert any value to a string: pass it to the :func:`repr` |
| 37 | or :func:`str` functions. Reverse quotes (``````) are equivalent to |
Benjamin Peterson | e6f0063 | 2008-05-26 01:03:56 +0000 | [diff] [blame] | 38 | :func:`repr`, but they are no longer used in modern Python code and are removed |
| 39 | in future versions of the language. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 40 | |
| 41 | The :func:`str` function is meant to return representations of values which are |
| 42 | fairly human-readable, while :func:`repr` is meant to generate representations |
| 43 | which can be read by the interpreter (or will force a :exc:`SyntaxError` if |
| 44 | there is not equivalent syntax). For objects which don't have a particular |
| 45 | representation for human consumption, :func:`str` will return the same value as |
| 46 | :func:`repr`. Many values, such as numbers or structures like lists and |
| 47 | dictionaries, have the same representation using either function. Strings and |
| 48 | floating point numbers, in particular, have two distinct representations. |
| 49 | |
| 50 | Some examples:: |
| 51 | |
| 52 | >>> s = 'Hello, world.' |
| 53 | >>> str(s) |
| 54 | 'Hello, world.' |
| 55 | >>> repr(s) |
| 56 | "'Hello, world.'" |
| 57 | >>> str(0.1) |
| 58 | '0.1' |
| 59 | >>> repr(0.1) |
| 60 | '0.10000000000000001' |
| 61 | >>> x = 10 * 3.25 |
| 62 | >>> y = 200 * 200 |
| 63 | >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...' |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 64 | >>> print(s) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 65 | The value of x is 32.5, and y is 40000... |
| 66 | >>> # The repr() of a string adds string quotes and backslashes: |
| 67 | ... hello = 'hello, world\n' |
| 68 | >>> hellos = repr(hello) |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 69 | >>> print(hellos) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 70 | 'hello, world\n' |
| 71 | >>> # The argument to repr() may be any Python object: |
| 72 | ... repr((x, y, ('spam', 'eggs'))) |
| 73 | "(32.5, 40000, ('spam', 'eggs'))" |
| 74 | >>> # reverse quotes are convenient in interactive sessions: |
| 75 | ... `x, y, ('spam', 'eggs')` |
| 76 | "(32.5, 40000, ('spam', 'eggs'))" |
| 77 | |
| 78 | Here are two ways to write a table of squares and cubes:: |
| 79 | |
| 80 | >>> for x in range(1, 11): |
Georg Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 81 | ... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ') |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 82 | ... # Note use of 'end' on previous line |
| 83 | ... print(repr(x*x*x).rjust(4)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 84 | ... |
| 85 | 1 1 1 |
| 86 | 2 4 8 |
| 87 | 3 9 27 |
| 88 | 4 16 64 |
| 89 | 5 25 125 |
| 90 | 6 36 216 |
| 91 | 7 49 343 |
| 92 | 8 64 512 |
| 93 | 9 81 729 |
| 94 | 10 100 1000 |
| 95 | |
Georg Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 96 | >>> for x in range(1, 11): |
Benjamin Peterson | e6f0063 | 2008-05-26 01:03:56 +0000 | [diff] [blame] | 97 | ... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 98 | ... |
| 99 | 1 1 1 |
| 100 | 2 4 8 |
| 101 | 3 9 27 |
| 102 | 4 16 64 |
| 103 | 5 25 125 |
| 104 | 6 36 216 |
| 105 | 7 49 343 |
| 106 | 8 64 512 |
| 107 | 9 81 729 |
| 108 | 10 100 1000 |
| 109 | |
| 110 | (Note that in the first example, one space between each column was added by the |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 111 | way :func:`print` works: it always adds spaces between its arguments.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 112 | |
| 113 | This example demonstrates the :meth:`rjust` method of string objects, which |
| 114 | right-justifies a string in a field of a given width by padding it with spaces |
| 115 | on the left. There are similar methods :meth:`ljust` and :meth:`center`. These |
| 116 | methods do not write anything, they just return a new string. If the input |
| 117 | string is too long, they don't truncate it, but return it unchanged; this will |
| 118 | mess up your column lay-out but that's usually better than the alternative, |
| 119 | which would be lying about a value. (If you really want truncation you can |
| 120 | always add a slice operation, as in ``x.ljust(n)[:n]``.) |
| 121 | |
| 122 | There is another method, :meth:`zfill`, which pads a numeric string on the left |
| 123 | with zeros. It understands about plus and minus signs:: |
| 124 | |
| 125 | >>> '12'.zfill(5) |
| 126 | '00012' |
| 127 | >>> '-3.14'.zfill(7) |
| 128 | '-003.14' |
| 129 | >>> '3.14159265359'.zfill(5) |
| 130 | '3.14159265359' |
| 131 | |
Benjamin Peterson | e6f0063 | 2008-05-26 01:03:56 +0000 | [diff] [blame] | 132 | Basic usage of the :meth:`str.format` method looks like this:: |
| 133 | |
| 134 | >>> print 'We are the {0} who say "{1}!"'.format('knights', 'Ni') |
| 135 | We are the knights who say "Ni!" |
| 136 | |
| 137 | The brackets and characters within them (called format fields) are replaced with |
| 138 | the objects passed into the format method. The number in the brackets refers to |
| 139 | the position of the object passed into the format method. :: |
| 140 | |
| 141 | >>> print '{0} and {1}'.format('spam', 'eggs') |
| 142 | spam and eggs |
| 143 | >>> print '{1} and {0}'.format('spam', 'eggs') |
| 144 | eggs and spam |
| 145 | |
| 146 | If keyword arguments are used in the format method, their values are referred to |
| 147 | by using the name of the argument. :: |
| 148 | |
| 149 | >>> print 'This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible') |
| 150 | This spam is absolutely horrible. |
| 151 | |
| 152 | Positional and keyword arguments can be arbitrarily combined:: |
| 153 | |
| 154 | >>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg') |
| 155 | The story of Bill, Manfred, and Georg. |
| 156 | |
| 157 | An optional ``':``` and format specifier can follow the field name. This also |
| 158 | greater control over how the value is formatted. The following example |
| 159 | truncates the Pi to three places after the decimal. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 160 | |
| 161 | >>> import math |
Benjamin Peterson | e6f0063 | 2008-05-26 01:03:56 +0000 | [diff] [blame] | 162 | >>> print('The value of PI is approximately {0:.3f}.'.format(math.pi)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 163 | The value of PI is approximately 3.142. |
| 164 | |
Benjamin Peterson | e6f0063 | 2008-05-26 01:03:56 +0000 | [diff] [blame] | 165 | Passing an integer after the ``':'`` will cause that field to be a minimum |
| 166 | number of characters wide. This is useful for making tables pretty.:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 167 | |
| 168 | >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} |
| 169 | >>> for name, phone in table.items(): |
Benjamin Peterson | e6f0063 | 2008-05-26 01:03:56 +0000 | [diff] [blame] | 170 | ... print('{0:10} ==> {1:10d}'.format(name, phone)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 171 | ... |
| 172 | Jack ==> 4098 |
| 173 | Dcab ==> 7678 |
| 174 | Sjoerd ==> 4127 |
| 175 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 176 | If you have a really long format string that you don't want to split up, it |
| 177 | would be nice if you could reference the variables to be formatted by name |
Benjamin Peterson | e6f0063 | 2008-05-26 01:03:56 +0000 | [diff] [blame] | 178 | instead of by position. This can be done by simply passing the dict and using |
| 179 | square brackets ``'[]'`` to access the keys :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 180 | |
| 181 | >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} |
Benjamin Peterson | e6f0063 | 2008-05-26 01:03:56 +0000 | [diff] [blame] | 182 | >>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table)) |
| 183 | Jack: 4098; Sjoerd: 4127; Dcab: 8637678 |
| 184 | |
| 185 | This could also be done by passing the table as keyword arguments with the '**' |
| 186 | notation.:: |
| 187 | |
| 188 | >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} |
| 189 | >>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 190 | Jack: 4098; Sjoerd: 4127; Dcab: 8637678 |
| 191 | |
| 192 | This is particularly useful in combination with the new built-in :func:`vars` |
| 193 | function, which returns a dictionary containing all local variables. |
| 194 | |
Benjamin Peterson | e6f0063 | 2008-05-26 01:03:56 +0000 | [diff] [blame] | 195 | For a complete overview of string formating with :meth:`str.format`, see |
| 196 | :ref:`formatstrings`. |
| 197 | |
| 198 | |
| 199 | Old string formatting |
| 200 | --------------------- |
| 201 | |
| 202 | The ``%`` operator can also be used for string formatting. It interprets the |
| 203 | left argument much like a :cfunc:`sprintf`\ -style format string to be applied |
| 204 | to the right argument, and returns the string resulting from this formatting |
| 205 | operation. For example:: |
| 206 | |
| 207 | >>> import math |
| 208 | >>> print 'The value of PI is approximately %5.3f.' % math.pi |
| 209 | The value of PI is approximately 3.142. |
| 210 | |
| 211 | Since :meth:`str.format` is quite new, a lot of Python code still uses the ``%`` |
| 212 | operator. However, because this old style of formatting will eventually removed |
| 213 | from the language :meth:`str.format` should generally be used. |
| 214 | |
| 215 | More information can be found in the :ref:`old-string-formatting` section. |
| 216 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 217 | |
| 218 | .. _tut-files: |
| 219 | |
| 220 | Reading and Writing Files |
| 221 | ========================= |
| 222 | |
| 223 | .. index:: |
| 224 | builtin: open |
| 225 | object: file |
| 226 | |
| 227 | :func:`open` returns a file object, and is most commonly used with two |
| 228 | arguments: ``open(filename, mode)``. |
| 229 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 230 | :: |
| 231 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 232 | >>> f = open('/tmp/workfile', 'w') |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 233 | >>> print(f) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 234 | <open file '/tmp/workfile', mode 'w' at 80a0960> |
| 235 | |
| 236 | The first argument is a string containing the filename. The second argument is |
| 237 | another string containing a few characters describing the way in which the file |
| 238 | will be used. *mode* can be ``'r'`` when the file will only be read, ``'w'`` |
| 239 | for only writing (an existing file with the same name will be erased), and |
| 240 | ``'a'`` opens the file for appending; any data written to the file is |
| 241 | automatically added to the end. ``'r+'`` opens the file for both reading and |
| 242 | writing. The *mode* argument is optional; ``'r'`` will be assumed if it's |
| 243 | omitted. |
| 244 | |
Christian Heimes | af98da1 | 2008-01-27 15:18:18 +0000 | [diff] [blame] | 245 | On Windows and the Macintosh, ``'b'`` appended to the mode opens the file in |
| 246 | binary mode, so there are also modes like ``'rb'``, ``'wb'``, and ``'r+b'``. |
| 247 | Windows makes a distinction between text and binary files; the end-of-line |
| 248 | characters in text files are automatically altered slightly when data is read or |
| 249 | written. This behind-the-scenes modification to file data is fine for ASCII |
| 250 | text files, but it'll corrupt binary data like that in :file:`JPEG` or |
| 251 | :file:`EXE` files. Be very careful to use binary mode when reading and writing |
| 252 | such files. On Unix, it doesn't hurt to append a ``'b'`` to the mode, so |
| 253 | you can use it platform-independently for all binary files. |
Skip Montanaro | 4e02c50 | 2007-09-26 01:10:12 +0000 | [diff] [blame] | 254 | |
| 255 | This behind-the-scenes modification to file data is fine for text files, but |
| 256 | will corrupt binary data like that in :file:`JPEG` or :file:`EXE` files. Be |
| 257 | very careful to use binary mode when reading and writing such files. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 258 | |
| 259 | |
| 260 | .. _tut-filemethods: |
| 261 | |
| 262 | Methods of File Objects |
| 263 | ----------------------- |
| 264 | |
| 265 | The rest of the examples in this section will assume that a file object called |
| 266 | ``f`` has already been created. |
| 267 | |
| 268 | To read a file's contents, call ``f.read(size)``, which reads some quantity of |
| 269 | data and returns it as a string. *size* is an optional numeric argument. When |
| 270 | *size* is omitted or negative, the entire contents of the file will be read and |
| 271 | returned; it's your problem if the file is twice as large as your machine's |
| 272 | memory. Otherwise, at most *size* bytes are read and returned. If the end of |
| 273 | the file has been reached, ``f.read()`` will return an empty string (``""``). |
| 274 | :: |
| 275 | |
| 276 | >>> f.read() |
| 277 | 'This is the entire file.\n' |
| 278 | >>> f.read() |
| 279 | '' |
| 280 | |
| 281 | ``f.readline()`` reads a single line from the file; a newline character (``\n``) |
| 282 | is left at the end of the string, and is only omitted on the last line of the |
| 283 | file if the file doesn't end in a newline. This makes the return value |
| 284 | unambiguous; if ``f.readline()`` returns an empty string, the end of the file |
| 285 | has been reached, while a blank line is represented by ``'\n'``, a string |
| 286 | containing only a single newline. :: |
| 287 | |
| 288 | >>> f.readline() |
| 289 | 'This is the first line of the file.\n' |
| 290 | >>> f.readline() |
| 291 | 'Second line of the file\n' |
| 292 | >>> f.readline() |
| 293 | '' |
| 294 | |
| 295 | ``f.readlines()`` returns a list containing all the lines of data in the file. |
| 296 | If given an optional parameter *sizehint*, it reads that many bytes from the |
| 297 | file and enough more to complete a line, and returns the lines from that. This |
| 298 | is often used to allow efficient reading of a large file by lines, but without |
| 299 | having to load the entire file in memory. Only complete lines will be returned. |
| 300 | :: |
| 301 | |
| 302 | >>> f.readlines() |
| 303 | ['This is the first line of the file.\n', 'Second line of the file\n'] |
| 304 | |
Thomas Wouters | 8ce81f7 | 2007-09-20 18:22:40 +0000 | [diff] [blame] | 305 | An alternative approach to reading lines is to loop over the file object. This is |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 306 | memory efficient, fast, and leads to simpler code:: |
| 307 | |
| 308 | >>> for line in f: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 309 | print(line, end='') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 310 | |
| 311 | This is the first line of the file. |
| 312 | Second line of the file |
| 313 | |
| 314 | The alternative approach is simpler but does not provide as fine-grained |
| 315 | control. Since the two approaches manage line buffering differently, they |
| 316 | should not be mixed. |
| 317 | |
| 318 | ``f.write(string)`` writes the contents of *string* to the file, returning |
| 319 | ``None``. :: |
| 320 | |
| 321 | >>> f.write('This is a test\n') |
| 322 | |
| 323 | To write something other than a string, it needs to be converted to a string |
| 324 | first:: |
| 325 | |
| 326 | >>> value = ('the answer', 42) |
| 327 | >>> s = str(value) |
| 328 | >>> f.write(s) |
| 329 | |
| 330 | ``f.tell()`` returns an integer giving the file object's current position in the |
| 331 | file, measured in bytes from the beginning of the file. To change the file |
| 332 | object's position, use ``f.seek(offset, from_what)``. The position is computed |
| 333 | from adding *offset* to a reference point; the reference point is selected by |
| 334 | the *from_what* argument. A *from_what* value of 0 measures from the beginning |
| 335 | of the file, 1 uses the current file position, and 2 uses the end of the file as |
| 336 | the reference point. *from_what* can be omitted and defaults to 0, using the |
| 337 | beginning of the file as the reference point. :: |
| 338 | |
| 339 | >>> f = open('/tmp/workfile', 'r+') |
| 340 | >>> f.write('0123456789abcdef') |
| 341 | >>> f.seek(5) # Go to the 6th byte in the file |
| 342 | >>> f.read(1) |
| 343 | '5' |
| 344 | >>> f.seek(-3, 2) # Go to the 3rd byte before the end |
| 345 | >>> f.read(1) |
| 346 | 'd' |
| 347 | |
| 348 | When you're done with a file, call ``f.close()`` to close it and free up any |
| 349 | system resources taken up by the open file. After calling ``f.close()``, |
| 350 | attempts to use the file object will automatically fail. :: |
| 351 | |
| 352 | >>> f.close() |
| 353 | >>> f.read() |
| 354 | Traceback (most recent call last): |
| 355 | File "<stdin>", line 1, in ? |
| 356 | ValueError: I/O operation on closed file |
| 357 | |
| 358 | File objects have some additional methods, such as :meth:`isatty` and |
| 359 | :meth:`truncate` which are less frequently used; consult the Library Reference |
| 360 | for a complete guide to file objects. |
| 361 | |
| 362 | |
| 363 | .. _tut-pickle: |
| 364 | |
| 365 | The :mod:`pickle` Module |
| 366 | ------------------------ |
| 367 | |
| 368 | .. index:: module: pickle |
| 369 | |
| 370 | Strings can easily be written to and read from a file. Numbers take a bit more |
| 371 | effort, since the :meth:`read` method only returns strings, which will have to |
| 372 | be passed to a function like :func:`int`, which takes a string like ``'123'`` |
| 373 | and returns its numeric value 123. However, when you want to save more complex |
| 374 | data types like lists, dictionaries, or class instances, things get a lot more |
| 375 | complicated. |
| 376 | |
| 377 | Rather than have users be constantly writing and debugging code to save |
| 378 | complicated data types, Python provides a standard module called :mod:`pickle`. |
| 379 | This is an amazing module that can take almost any Python object (even some |
| 380 | forms of Python code!), and convert it to a string representation; this process |
| 381 | is called :dfn:`pickling`. Reconstructing the object from the string |
| 382 | representation is called :dfn:`unpickling`. Between pickling and unpickling, |
| 383 | the string representing the object may have been stored in a file or data, or |
| 384 | sent over a network connection to some distant machine. |
| 385 | |
| 386 | If you have an object ``x``, and a file object ``f`` that's been opened for |
| 387 | writing, the simplest way to pickle the object takes only one line of code:: |
| 388 | |
| 389 | pickle.dump(x, f) |
| 390 | |
| 391 | To unpickle the object again, if ``f`` is a file object which has been opened |
| 392 | for reading:: |
| 393 | |
| 394 | x = pickle.load(f) |
| 395 | |
| 396 | (There are other variants of this, used when pickling many objects or when you |
| 397 | don't want to write the pickled data to a file; consult the complete |
| 398 | documentation for :mod:`pickle` in the Python Library Reference.) |
| 399 | |
| 400 | :mod:`pickle` is the standard way to make Python objects which can be stored and |
| 401 | reused by other programs or by a future invocation of the same program; the |
| 402 | technical term for this is a :dfn:`persistent` object. Because :mod:`pickle` is |
| 403 | so widely used, many authors who write Python extensions take care to ensure |
| 404 | that new data types such as matrices can be properly pickled and unpickled. |
| 405 | |
| 406 | |