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