rest25/tutorial/inputoutput.rst => rest262/tutorial/inputoutput.rst
22.. index:: module: string
23
24Often you'll want more control over the formatting of your output than simply
25printing space-separated values.  There are two ways to format your output; the
26first way is to do all the string handling yourself; using string slicing and
27concatenation operations you can create any layout you can imagine.  The
28standard module :mod:`string` contains some useful operations for padding
29strings to a given column width; these will be discussed shortly.  The second
n30-way is to use the ``%`` operator with a string as the left argument.  The ``%``
n30+way is to use the :meth:`str.format` method.
31-operator interprets the left argument much like a :cfunc:`sprintf`\ -style
32-format string to be applied to the right argument, and returns the string
33-resulting from this formatting operation.
34
35One question remains, of course: how do you convert values to strings? Luckily,
36Python has ways to convert any value to a string: pass it to the :func:`repr`
n37-or :func:`str` functions.  Reverse quotes (``````) are equivalent to
n34+or :func:`str` functions.
38-:func:`repr`, but they are no longer used in modern Python code and will likely
39-not be in future versions of the language.
40
41The :func:`str` function is meant to return representations of values which are
42fairly human-readable, while :func:`repr` is meant to generate representations
43which can be read by the interpreter (or will force a :exc:`SyntaxError` if
44there is not equivalent syntax).  For objects which don't have a particular
45representation for human consumption, :func:`str` will return the same value as
46:func:`repr`.  Many values, such as numbers or structures like lists and
47dictionaries, have the same representation using either function.  Strings and
66   >>> # The repr() of a string adds string quotes and backslashes:
67   ... hello = 'hello, world\n'
68   >>> hellos = repr(hello)
69   >>> print hellos
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'))"
n74-   >>> # reverse quotes are convenient in interactive sessions:
75-   ... `x, y, ('spam', 'eggs')`
76-   "(32.5, 40000, ('spam', 'eggs'))"
77
78Here are two ways to write a table of squares and cubes::
79
80   >>> for x in range(1, 11):
81   ...     print repr(x).rjust(2), repr(x*x).rjust(3),
82   ...     # Note trailing comma on previous line
83   ...     print repr(x*x*x).rjust(4)
84   ...
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
n87+ 
95   >>> for x in range(1,11):
n96-   ...     print '%2d %3d %4d' % (x, x*x, x*x*x)
n89+   ...     print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)
97-   ... 
90+   ...
98    1   1    1
99    2   4    8
100    3   9   27
101    4  16   64
102    5  25  125
103    6  36  216
104    7  49  343
105    8  64  512
106    9  81  729
107   10 100 1000
108
n109-(Note that one space between each column was added by the way :keyword:`print`
n102+(Note that in the first example, one space between each column was added by the
110-works: it always adds spaces between its arguments.)
103+way :keyword:`print` works: it always adds spaces between its arguments.)
111
112This example demonstrates the :meth:`rjust` method of string objects, which
113right-justifies a string in a field of a given width by padding it with spaces
114on the left.  There are similar methods :meth:`ljust` and :meth:`center`.  These
115methods do not write anything, they just return a new string.  If the input
116string is too long, they don't truncate it, but return it unchanged; this will
117mess up your column lay-out but that's usually better than the alternative,
118which would be lying about a value.  (If you really want truncation you can
123
124   >>> '12'.zfill(5)
125   '00012'
126   >>> '-3.14'.zfill(7)
127   '-003.14'
128   >>> '3.14159265359'.zfill(5)
129   '3.14159265359'
130
n131-Using the ``%`` operator looks like this::
n124+Basic usage of the :meth:`str.format` method looks like this::
125+ 
126+   >>> print 'We are the {0} who say "{1}!"'.format('knights', 'Ni')
127+   We are the knights who say "Ni!"
128+ 
129+The brackets and characters within them (called format fields) are replaced with
130+the objects passed into the format method.  The number in the brackets refers to
131+the position of the object passed into the format method. ::
132+ 
133+   >>> print '{0} and {1}'.format('spam', 'eggs')
134+   spam and eggs
135+   >>> print '{1} and {0}'.format('spam', 'eggs')
136+   eggs and spam
137+ 
138+If keyword arguments are used in the format method, their values are referred to
139+by using the name of the argument. ::
140+ 
141+   >>> print 'This {food} is {adjective}.'.format(
142+   ...       food='spam', adjective='absolutely horrible')
143+   This spam is absolutely horrible.
144+ 
145+Positional and keyword arguments can be arbitrarily combined::
146+ 
147+   >>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
148+   ...                                                    other='Georg')
149+   The story of Bill, Manfred, and Georg.
150+ 
151+An optional ``':'`` and format specifier can follow the field name. This also
152+greater control over how the value is formatted.  The following example
153+truncates the Pi to three places after the decimal.
154+ 
155+   >>> import math
156+   >>> print 'The value of PI is approximately {0:.3f}.'.format(math.pi)
157+   The value of PI is approximately 3.142.
158+ 
159+Passing an integer after the ``':'`` will cause that field to be a minimum
160+number of characters wide.  This is useful for making tables pretty.::
161+ 
162+   >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
163+   >>> for name, phone in table.items():
164+   ...     print '{0:10} ==> {1:10d}'.format(name, phone)
165+   ...
166+   Jack       ==>       4098
167+   Dcab       ==>       7678
168+   Sjoerd     ==>       4127
169+ 
170+If you have a really long format string that you don't want to split up, it
171+would be nice if you could reference the variables to be formatted by name
172+instead of by position.  This can be done by simply passing the dict and using
173+square brackets ``'[]'`` to access the keys ::
174+ 
175+   >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
176+   >>> print ('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
177+   ...        'Dcab: {0[Dcab]:d}'.format(table))
178+   Jack: 4098; Sjoerd: 4127; Dcab: 8637678
179+ 
180+This could also be done by passing the table as keyword arguments with the '**'
181+notation.::
182+ 
183+   >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
184+   >>> print 'Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)
185+   Jack: 4098; Sjoerd: 4127; Dcab: 8637678
186+ 
187+This is particularly useful in combination with the new built-in :func:`vars`
188+function, which returns a dictionary containing all local variables.
189+ 
190+For a complete overview of string formating with :meth:`str.format`, see
191+:ref:`formatstrings`.
192+ 
193+ 
194+Old string formatting
195+---------------------
196+ 
197+The ``%`` operator can also be used for string formatting. It interprets the
198+left argument much like a :cfunc:`sprintf`\ -style format string to be applied
199+to the right argument, and returns the string resulting from this formatting
200+operation. For example::
132
133   >>> import math
134   >>> print 'The value of PI is approximately %5.3f.' % math.pi
135   The value of PI is approximately 3.142.
136
n137-If there is more than one format in the string, you need to pass a tuple as
n206+Since :meth:`str.format` is quite new, a lot of Python code still uses the ``%``
138-right operand, as in this example::
207+operator. However, because this old style of formatting will eventually removed
208+from the language :meth:`str.format` should generally be used.
139
n140-   >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
n210+More information can be found in the :ref:`string-formatting` section.
141-   >>> for name, phone in table.items():
142-   ...     print '%-10s ==> %10d' % (name, phone)
143-   ... 
144-   Jack       ==>       4098
145-   Dcab       ==>       7678
146-   Sjoerd     ==>       4127
147- 
148-Most formats work exactly as in C and require that you pass the proper type;
149-however, if you don't you get an exception, not a core dump. The ``%s`` format
150-is more relaxed: if the corresponding argument is not a string object, it is
151-converted to string using the :func:`str` built-in function.  Using ``*`` to
152-pass the width or precision in as a separate (integer) argument is supported.
153-The C formats ``%n`` and ``%p`` are not supported.
154- 
155-If you have a really long format string that you don't want to split up, it
156-would be nice if you could reference the variables to be formatted by name
157-instead of by position.  This can be done by using form ``%(name)format``, as
158-shown here::
159- 
160-   >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
161-   >>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
162-   Jack: 4098; Sjoerd: 4127; Dcab: 8637678
163- 
164-This is particularly useful in combination with the new built-in :func:`vars`
165-function, which returns a dictionary containing all local variables.
166
167
168.. _tut-files:
169
170Reading and Writing Files
171=========================
172
173.. index::
174   builtin: open
175   object: file
176
177:func:`open` returns a file object, and is most commonly used with two
178arguments: ``open(filename, mode)``.
179
n180-.. % Opening files
181- 
182::
183
n184-   >>> f=open('/tmp/workfile', 'w')
n227+   >>> f = open('/tmp/workfile', 'w')
185   >>> print f
186   <open file '/tmp/workfile', mode 'w' at 80a0960>
187
188The first argument is a string containing the filename.  The second argument is
189another string containing a few characters describing the way in which the file
190will be used.  *mode* can be ``'r'`` when the file will only be read, ``'w'``
191for only writing (an existing file with the same name will be erased), and
192``'a'`` opens the file for appending; any data written to the file is
193automatically added to the end.  ``'r+'`` opens the file for both reading and
194writing. The *mode* argument is optional; ``'r'`` will be assumed if it's
195omitted.
196
n197-On Windows and the Macintosh, ``'b'`` appended to the mode opens the file in
n240+On Windows, ``'b'`` appended to the mode opens the file in binary mode, so there
198-binary mode, so there are also modes like ``'rb'``, ``'wb'``, and ``'r+b'``.
241+are also modes like ``'rb'``, ``'wb'``, and ``'r+b'``.  Windows makes a
199-Windows makes a distinction between text and binary files; the end-of-line
242+distinction between text and binary files; the end-of-line characters in text
200-characters in text files are automatically altered slightly when data is read or
243+files are automatically altered slightly when data is read or written.  This
201-written.  This behind-the-scenes modification to file data is fine for ASCII
244+behind-the-scenes modification to file data is fine for ASCII text files, but
202-text files, but it'll corrupt binary data like that in :file:`JPEG` or
245+it'll corrupt binary data like that in :file:`JPEG` or :file:`EXE` files.  Be
203-:file:`EXE` files.  Be very careful to use binary mode when reading and writing
246+very careful to use binary mode when reading and writing such files.  On Unix,
204-such files.
247+it doesn't hurt to append a ``'b'`` to the mode, so you can use it
248+platform-independently for all binary files.
205
206
207.. _tut-filemethods:
208
209Methods of File Objects
210-----------------------
211
212The rest of the examples in this section will assume that a file object called
244file and enough more to complete a line, and returns the lines from that.  This
245is often used to allow efficient reading of a large file by lines, but without
246having to load the entire file in memory.  Only complete lines will be returned.
247::
248
249   >>> f.readlines()
250   ['This is the first line of the file.\n', 'Second line of the file\n']
251
n252-An alternate approach to reading lines is to loop over the file object. This is
n296+An alternative approach to reading lines is to loop over the file object. This is
253memory efficient, fast, and leads to simpler code::
254
255   >>> for line in f:
256           print line,
257
258   This is the first line of the file.
259   Second line of the file
260
281the *from_what* argument.  A *from_what* value of 0 measures from the beginning
282of the file, 1 uses the current file position, and 2 uses the end of the file as
283the reference point.  *from_what* can be omitted and defaults to 0, using the
284beginning of the file as the reference point. ::
285
286   >>> f = open('/tmp/workfile', 'r+')
287   >>> f.write('0123456789abcdef')
288   >>> f.seek(5)     # Go to the 6th byte in the file
n289-   >>> f.read(1)        
n333+   >>> f.read(1)
290   '5'
291   >>> f.seek(-3, 2) # Go to the 3rd byte before the end
292   >>> f.read(1)
293   'd'
294
295When you're done with a file, call ``f.close()`` to close it and free up any
296system resources taken up by the open file.  After calling ``f.close()``,
297attempts to use the file object will automatically fail. ::
298
299   >>> f.close()
300   >>> f.read()
301   Traceback (most recent call last):
302     File "<stdin>", line 1, in ?
303   ValueError: I/O operation on closed file
n348+ 
349+It is good practice to use the :keyword:`with` keyword when dealing with file
350+objects.  This has the advantage that the file is properly closed after its
351+suite finishes, even if an exception is raised on the way.  It is also much
352+shorter than writing equivalent :keyword:`try`\ -\ :keyword:`finally` blocks::
353+ 
354+    >>> with open('/tmp/workfile', 'r') as f:
355+    ...     read_data = f.read()
356+    >>> f.closed
357+    True
304
305File objects have some additional methods, such as :meth:`isatty` and
306:meth:`truncate` which are less frequently used; consult the Library Reference
307for a complete guide to file objects.
308
309
310.. _tut-pickle:
311
317Strings can easily be written to and read from a file. Numbers take a bit more
318effort, since the :meth:`read` method only returns strings, which will have to
319be passed to a function like :func:`int`, which takes a string like ``'123'``
320and returns its numeric value 123.  However, when you want to save more complex
321data types like lists, dictionaries, or class instances, things get a lot more
322complicated.
323
324Rather than have users be constantly writing and debugging code to save
n325-complicated data types, Python provides a standard module called :mod:`pickle`
n379+complicated data types, Python provides a standard module called :mod:`pickle`.
326-(XXX reference: ../lib/module-pickle.html).  This is an amazing module that can
380+This is an amazing module that can take almost any Python object (even some
327-take almost any Python object (even some forms of Python code!), and convert it
381+forms of Python code!), and convert it to a string representation; this process
328-to a string representation; this process is called :dfn:`pickling`.
382+is called :dfn:`pickling`.  Reconstructing the object from the string
329-Reconstructing the object from the string representation is called
383+representation is called :dfn:`unpickling`.  Between pickling and unpickling,
330-:dfn:`unpickling`.  Between pickling and unpickling, the string representing the
384+the string representing the object may have been stored in a file or data, or
331-object may have been stored in a file or data, or sent over a network connection
385+sent over a network connection to some distant machine.
332-to some distant machine.
333
334If you have an object ``x``, and a file object ``f`` that's been opened for
335writing, the simplest way to pickle the object takes only one line of code::
336
337   pickle.dump(x, f)
338
339To unpickle the object again, if ``f`` is a file object which has been opened
340for reading::
341
342   x = pickle.load(f)
343
344(There are other variants of this, used when pickling many objects or when you
345don't want to write the pickled data to a file; consult the complete
n346-documentation for :mod:`pickle` (XXX reference: ../lib/module-pickle.html) in
n399+documentation for :mod:`pickle` in the Python Library Reference.)
347-the Python Library Reference (XXX reference: ../lib/).)
348
t349-:mod:`pickle` (XXX reference: ../lib/module-pickle.html) is the standard way to
t401+:mod:`pickle` is the standard way to make Python objects which can be stored and
350-make Python objects which can be stored and reused by other programs or by a
402+reused by other programs or by a future invocation of the same program; the
351-future invocation of the same program; the technical term for this is a
403+technical term for this is a :dfn:`persistent` object.  Because :mod:`pickle` is
352-:dfn:`persistent` object.  Because :mod:`pickle` (XXX reference: ../lib/module-
353-pickle.html) is so widely used, many authors who write Python extensions take
404+so widely used, many authors who write Python extensions take care to ensure
354-care to ensure that new data types such as matrices can be properly pickled and
405+that new data types such as matrices can be properly pickled and unpickled.
355-unpickled.
356
357
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op