Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / src / nas,5.n2.os.2 / lib / python / html / python / tut / node9.html
CommitLineData
86530b38
AT
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<html>
3<head>
4<link rel="STYLESHEET" href="tut.css" type='text/css' />
5<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
6<link rel='start' href='../index.html' title='Python Documentation Index' />
7<link rel="first" href="tut.html" title='Python Tutorial' />
8<link rel='contents' href='node2.html' title="Contents" />
9<link rel='index' href='node19.html' title='Index' />
10<link rel='last' href='about.html' title='About this document...' />
11<link rel='help' href='about.html' title='About this document...' />
12<link rel="next" href="node10.html" />
13<link rel="prev" href="node8.html" />
14<link rel="parent" href="tut.html" />
15<link rel="next" href="node10.html" />
16<meta name='aesop' content='information' />
17<title>7. Input and Output </title>
18</head>
19<body>
20<DIV CLASS="navigation">
21<div id='top-navigation-panel' xml:id='top-navigation-panel'>
22<table align="center" width="100%" cellpadding="0" cellspacing="2">
23<tr>
24<td class='online-navigation'><a rel="prev" title="6. Modules"
25 href="node8.html"><img src='../icons/previous.png'
26 border='0' height='32' alt='Previous Page' width='32' /></A></td>
27<td class='online-navigation'><a rel="parent" title="Python Tutorial"
28 href="tut.html"><img src='../icons/up.png'
29 border='0' height='32' alt='Up One Level' width='32' /></A></td>
30<td class='online-navigation'><a rel="next" title="8. Errors and Exceptions"
31 href="node10.html"><img src='../icons/next.png'
32 border='0' height='32' alt='Next Page' width='32' /></A></td>
33<td align="center" width="100%">Python Tutorial</td>
34<td class='online-navigation'><a rel="contents" title="Table of Contents"
35 href="node2.html"><img src='../icons/contents.png'
36 border='0' height='32' alt='Contents' width='32' /></A></td>
37<td class='online-navigation'><img src='../icons/blank.png'
38 border='0' height='32' alt='' width='32' /></td>
39<td class='online-navigation'><a rel="index" title="Index"
40 href="node19.html"><img src='../icons/index.png'
41 border='0' height='32' alt='Index' width='32' /></A></td>
42</tr></table>
43<div class='online-navigation'>
44<b class="navlabel">Previous:</b>
45<a class="sectref" rel="prev" href="node8.html">6. Modules</A>
46<b class="navlabel">Up:</b>
47<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
48<b class="navlabel">Next:</b>
49<a class="sectref" rel="next" href="node10.html">8. Errors and Exceptions</A>
50</div>
51<hr /></div>
52</DIV>
53<!--End of Navigation Panel-->
54<div class='online-navigation'>
55<!--Table of Child-Links-->
56<A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a>
57
58<UL CLASS="ChildLinks">
59<LI><A href="node9.html#SECTION009100000000000000000">7.1 Fancier Output Formatting</a>
60<LI><A href="node9.html#SECTION009200000000000000000">7.2 Reading and Writing Files</a>
61<UL>
62<LI><A href="node9.html#SECTION009210000000000000000">7.2.1 Methods of File Objects</a>
63<LI><A href="node9.html#SECTION009220000000000000000">7.2.2 The <tt class="module">pickle</tt> Module</a>
64</ul></ul>
65<!--End of Table of Child-Links-->
66</div>
67<HR>
68
69<H1><A NAME="SECTION009000000000000000000"></A><A NAME="io"></A>
70<BR>
717. Input and Output
72</H1>
73
74<P>
75There are several ways to present the output of a program; data can be
76printed in a human-readable form, or written to a file for future use.
77This chapter will discuss some of the possibilities.
78
79<P>
80
81<H1><A NAME="SECTION009100000000000000000"></A><A NAME="formatting"></A>
82<BR>
837.1 Fancier Output Formatting
84</H1>
85
86<P>
87So far we've encountered two ways of writing values: <em>expression
88statements</em> and the <tt class="keyword">print</tt> statement. (A third way is using
89the <tt class="method">write()</tt> method of file objects; the standard output file
90can be referenced as <code>sys.stdout</code>. See the Library Reference for
91more information on this.)
92
93<P>
94Often you'll want more control over the formatting of your output than
95simply printing space-separated values. There are two ways to format
96your output; the first way is to do all the string handling yourself;
97using string slicing and concatenation operations you can create any
98layout you can imagine. The standard module
99<tt class="module">string</tt><a id='l2h-29' xml:id='l2h-29'></a> contains some useful operations
100for padding strings to a given column width; these will be discussed
101shortly. The second way is to use the <code>%</code> operator with a
102string as the left argument. The <code>%</code> operator interprets the
103left argument much like a <tt class="cfunction">sprintf()</tt>-style format
104string to be applied to the right argument, and returns the string
105resulting from this formatting operation.
106
107<P>
108One question remains, of course: how do you convert values to strings?
109Luckily, Python has ways to convert any value to a string: pass it to
110the <tt class="function">repr()</tt> or <tt class="function">str()</tt> functions. Reverse quotes
111(<code>``</code>) are equivalent to <tt class="function">repr()</tt>, but they are no
112longer used in modern Python code and will likely not be in future
113versions of the language.
114
115<P>
116The <tt class="function">str()</tt> function is meant to return representations of
117values which are fairly human-readable, while <tt class="function">repr()</tt> is
118meant to generate representations which can be read by the interpreter
119(or will force a <tt class="exception">SyntaxError</tt> if there is not equivalent
120syntax). For objects which don't have a particular representation for
121human consumption, <tt class="function">str()</tt> will return the same value as
122<tt class="function">repr()</tt>. Many values, such as numbers or structures like
123lists and dictionaries, have the same representation using either
124function. Strings and floating point numbers, in particular, have two
125distinct representations.
126
127<P>
128Some examples:
129
130<P>
131<div class="verbatim"><pre>
132&gt;&gt;&gt; s = 'Hello, world.'
133&gt;&gt;&gt; str(s)
134'Hello, world.'
135&gt;&gt;&gt; repr(s)
136"'Hello, world.'"
137&gt;&gt;&gt; str(0.1)
138'0.1'
139&gt;&gt;&gt; repr(0.1)
140'0.10000000000000001'
141&gt;&gt;&gt; x = 10 * 3.25
142&gt;&gt;&gt; y = 200 * 200
143&gt;&gt;&gt; s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
144&gt;&gt;&gt; print s
145The value of x is 32.5, and y is 40000...
146&gt;&gt;&gt; # The repr() of a string adds string quotes and backslashes:
147... hello = 'hello, world\n'
148&gt;&gt;&gt; hellos = repr(hello)
149&gt;&gt;&gt; print hellos
150'hello, world\n'
151&gt;&gt;&gt; # The argument to repr() may be any Python object:
152... repr((x, y, ('spam', 'eggs')))
153"(32.5, 40000, ('spam', 'eggs'))"
154&gt;&gt;&gt; # reverse quotes are convenient in interactive sessions:
155... `x, y, ('spam', 'eggs')`
156"(32.5, 40000, ('spam', 'eggs'))"
157</pre></div>
158
159<P>
160Here are two ways to write a table of squares and cubes:
161
162<P>
163<div class="verbatim"><pre>
164&gt;&gt;&gt; for x in range(1, 11):
165... print repr(x).rjust(2), repr(x*x).rjust(3),
166... # Note trailing comma on previous line
167... print repr(x*x*x).rjust(4)
168...
169 1 1 1
170 2 4 8
171 3 9 27
172 4 16 64
173 5 25 125
174 6 36 216
175 7 49 343
176 8 64 512
177 9 81 729
17810 100 1000
179&gt;&gt;&gt; for x in range(1,11):
180... print '%2d %3d %4d' % (x, x*x, x*x*x)
181...
182 1 1 1
183 2 4 8
184 3 9 27
185 4 16 64
186 5 25 125
187 6 36 216
188 7 49 343
189 8 64 512
190 9 81 729
19110 100 1000
192</pre></div>
193
194<P>
195(Note that one space between each column was added by the way
196<tt class="keyword">print</tt> works: it always adds spaces between its arguments.)
197
198<P>
199This example demonstrates the <tt class="method">rjust()</tt> method of string objects,
200which right-justifies a string in a field of a given width by padding
201it with spaces on the left. There are similar methods
202<tt class="method">ljust()</tt> and <tt class="method">center()</tt>. These
203methods do not write anything, they just return a new string. If
204the input string is too long, they don't truncate it, but return it
205unchanged; this will mess up your column lay-out but that's usually
206better than the alternative, which would be lying about a value. (If
207you really want truncation you can always add a slice operation, as in
208"<tt class="samp">x.ljust(n)[:n]</tt>".)
209
210<P>
211There is another method, <tt class="method">zfill()</tt>, which pads a
212numeric string on the left with zeros. It understands about plus and
213minus signs:
214
215<P>
216<div class="verbatim"><pre>
217&gt;&gt;&gt; '12'.zfill(5)
218'00012'
219&gt;&gt;&gt; '-3.14'.zfill(7)
220'-003.14'
221&gt;&gt;&gt; '3.14159265359'.zfill(5)
222'3.14159265359'
223</pre></div>
224
225<P>
226Using the <code>%</code> operator looks like this:
227
228<P>
229<div class="verbatim"><pre>
230&gt;&gt;&gt; import math
231&gt;&gt;&gt; print 'The value of PI is approximately %5.3f.' % math.pi
232The value of PI is approximately 3.142.
233</pre></div>
234
235<P>
236If there is more than one format in the string, you need to pass a
237tuple as right operand, as in this example:
238
239<P>
240<div class="verbatim"><pre>
241&gt;&gt;&gt; table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
242&gt;&gt;&gt; for name, phone in table.items():
243... print '%-10s ==&gt; %10d' % (name, phone)
244...
245Jack ==&gt; 4098
246Dcab ==&gt; 7678
247Sjoerd ==&gt; 4127
248</pre></div>
249
250<P>
251Most formats work exactly as in C and require that you pass the proper
252type; however, if you don't you get an exception, not a core dump.
253The <code>%s</code> format is more relaxed: if the corresponding argument is
254not a string object, it is converted to string using the
255<tt class="function">str()</tt> built-in function. Using <code>*</code> to pass the width
256or precision in as a separate (integer) argument is supported. The
257C formats <code>%n</code> and <code>%p</code> are not supported.
258
259<P>
260If you have a really long format string that you don't want to split
261up, it would be nice if you could reference the variables to be
262formatted by name instead of by position. This can be done by using
263form <code>%(name)format</code>, as shown here:
264
265<P>
266<div class="verbatim"><pre>
267&gt;&gt;&gt; table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
268&gt;&gt;&gt; print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
269Jack: 4098; Sjoerd: 4127; Dcab: 8637678
270</pre></div>
271
272<P>
273This is particularly useful in combination with the new built-in
274<tt class="function">vars()</tt> function, which returns a dictionary containing all
275local variables.
276
277<P>
278
279<H1><A NAME="SECTION009200000000000000000"></A><A NAME="files"></A>
280<BR>
2817.2 Reading and Writing Files
282</H1>
283
284<P>
285<tt class="function">open()</tt><a id='l2h-30' xml:id='l2h-30'></a> returns a file
286object<a id='l2h-31' xml:id='l2h-31'></a>, and is most commonly used with two arguments:
287"<tt class="samp">open(<var>filename</var>, <var>mode</var>)</tt>".
288
289<P>
290<div class="verbatim"><pre>
291&gt;&gt;&gt; f=open('/tmp/workfile', 'w')
292&gt;&gt;&gt; print f
293&lt;open file '/tmp/workfile', mode 'w' at 80a0960&gt;
294</pre></div>
295
296<P>
297The first argument is a string containing the filename. The second
298argument is another string containing a few characters describing the
299way in which the file will be used. <var>mode</var> can be <code>'r'</code> when
300the file will only be read, <code>'w'</code> for only writing (an existing
301file with the same name will be erased), and <code>'a'</code> opens the file
302for appending; any data written to the file is automatically added to
303the end. <code>'r+'</code> opens the file for both reading and writing.
304The <var>mode</var> argument is optional; <code>'r'</code> will be assumed if
305it's omitted.
306
307<P>
308On Windows and the Macintosh, <code>'b'</code> appended to the
309mode opens the file in binary mode, so there are also modes like
310<code>'rb'</code>, <code>'wb'</code>, and <code>'r+b'</code>. Windows makes a
311distinction between text and binary files; the end-of-line characters
312in text files are automatically altered slightly when data is read or
313written. This behind-the-scenes modification to file data is fine for
314ASCII text files, but it'll corrupt binary data like that in <span class="file">JPEG</span> or
315<span class="file">EXE</span> files. Be very careful to use binary mode when reading and
316writing such files.
317
318<P>
319
320<H2><A NAME="SECTION009210000000000000000"></A><A NAME="fileMethods"></A>
321<BR>
3227.2.1 Methods of File Objects
323</H2>
324
325<P>
326The rest of the examples in this section will assume that a file
327object called <code>f</code> has already been created.
328
329<P>
330To read a file's contents, call <code>f.read(<var>size</var>)</code>, which reads
331some quantity of data and returns it as a string. <var>size</var> is an
332optional numeric argument. When <var>size</var> is omitted or negative,
333the entire contents of the file will be read and returned; it's your
334problem if the file is twice as large as your machine's memory.
335Otherwise, at most <var>size</var> bytes are read and returned. If the end
336of the file has been reached, <code>f.read()</code> will return an empty
337string (<code>""</code>).
338<div class="verbatim"><pre>
339&gt;&gt;&gt; f.read()
340'This is the entire file.\n'
341&gt;&gt;&gt; f.read()
342''
343</pre></div>
344
345<P>
346<code>f.readline()</code> reads a single line from the file; a newline
347character (<code>&#92;n</code>) is left at the end of the string, and is only
348omitted on the last line of the file if the file doesn't end in a
349newline. This makes the return value unambiguous; if
350<code>f.readline()</code> returns an empty string, the end of the file has
351been reached, while a blank line is represented by <code>'&#92;n'</code>, a
352string containing only a single newline.
353
354<P>
355<div class="verbatim"><pre>
356&gt;&gt;&gt; f.readline()
357'This is the first line of the file.\n'
358&gt;&gt;&gt; f.readline()
359'Second line of the file\n'
360&gt;&gt;&gt; f.readline()
361''
362</pre></div>
363
364<P>
365<code>f.readlines()</code> returns a list containing all the lines of data
366in the file. If given an optional parameter <var>sizehint</var>, it reads
367that many bytes from the file and enough more to complete a line, and
368returns the lines from that. This is often used to allow efficient
369reading of a large file by lines, but without having to load the
370entire file in memory. Only complete lines will be returned.
371
372<P>
373<div class="verbatim"><pre>
374&gt;&gt;&gt; f.readlines()
375['This is the first line of the file.\n', 'Second line of the file\n']
376</pre></div>
377
378<P>
379An alternate approach to reading lines is to loop over the file object.
380This is memory efficient, fast, and leads to simpler code:
381
382<P>
383<div class="verbatim"><pre>
384&gt;&gt;&gt; for line in f:
385 print line,
386
387This is the first line of the file.
388Second line of the file
389</pre></div>
390
391<P>
392The alternative approach is simpler but does not provide as fine-grained
393control. Since the two approaches manage line buffering differently,
394they should not be mixed.
395
396<P>
397<code>f.write(<var>string</var>)</code> writes the contents of <var>string</var> to
398the file, returning <code>None</code>.
399
400<P>
401<div class="verbatim"><pre>
402&gt;&gt;&gt; f.write('This is a test\n')
403</pre></div>
404
405<P>
406To write something other than a string, it needs to be converted to a
407string first:
408
409<P>
410<div class="verbatim"><pre>
411&gt;&gt;&gt; value = ('the answer', 42)
412&gt;&gt;&gt; s = str(value)
413&gt;&gt;&gt; f.write(s)
414</pre></div>
415
416<P>
417<code>f.tell()</code> returns an integer giving the file object's current
418position in the file, measured in bytes from the beginning of the
419file. To change the file object's position, use
420"<tt class="samp">f.seek(<var>offset</var>, <var>from_what</var>)</tt>". The position is
421computed from adding <var>offset</var> to a reference point; the reference
422point is selected by the <var>from_what</var> argument. A
423<var>from_what</var> value of 0 measures from the beginning of the file, 1
424uses the current file position, and 2 uses the end of the file as the
425reference point. <var>from_what</var> can be omitted and defaults to 0,
426using the beginning of the file as the reference point.
427
428<P>
429<div class="verbatim"><pre>
430&gt;&gt;&gt; f = open('/tmp/workfile', 'r+')
431&gt;&gt;&gt; f.write('0123456789abcdef')
432&gt;&gt;&gt; f.seek(5) # Go to the 6th byte in the file
433&gt;&gt;&gt; f.read(1)
434'5'
435&gt;&gt;&gt; f.seek(-3, 2) # Go to the 3rd byte before the end
436&gt;&gt;&gt; f.read(1)
437'd'
438</pre></div>
439
440<P>
441When you're done with a file, call <code>f.close()</code> to close it and
442free up any system resources taken up by the open file. After calling
443<code>f.close()</code>, attempts to use the file object will automatically fail.
444
445<P>
446<div class="verbatim"><pre>
447&gt;&gt;&gt; f.close()
448&gt;&gt;&gt; f.read()
449Traceback (most recent call last):
450 File "&lt;stdin&gt;", line 1, in ?
451ValueError: I/O operation on closed file
452</pre></div>
453
454<P>
455File objects have some additional methods, such as
456<tt class="method">isatty()</tt> and <tt class="method">truncate()</tt> which are less frequently
457used; consult the Library Reference for a complete guide to file
458objects.
459
460<P>
461
462<H2><A NAME="SECTION009220000000000000000"></A><A NAME="pickle"></A>
463<BR>
4647.2.2 The <tt class="module">pickle</tt> Module
465</H2>
466<a id='l2h-32' xml:id='l2h-32'></a>
467
468<P>
469Strings can easily be written to and read from a file. Numbers take a
470bit more effort, since the <tt class="method">read()</tt> method only returns
471strings, which will have to be passed to a function like
472<tt class="function">int()</tt>, which takes a string like <code>'123'</code> and
473returns its numeric value 123. However, when you want to save more
474complex data types like lists, dictionaries, or class instances,
475things get a lot more complicated.
476
477<P>
478Rather than have users be constantly writing and debugging code to
479save complicated data types, Python provides a standard module called
480<a class="ulink" href="../lib/module-pickle.html"
481 ><tt class="module">pickle</tt></a>. This is an
482amazing module that can take almost
483any Python object (even some forms of Python code!), and convert it to
484a string representation; this process is called <i class="dfn">pickling</i>.
485Reconstructing the object from the string representation is called
486<i class="dfn">unpickling</i>. Between pickling and unpickling, the string
487representing the object may have been stored in a file or data, or
488sent over a network connection to some distant machine.
489
490<P>
491If you have an object <code>x</code>, and a file object <code>f</code> that's been
492opened for writing, the simplest way to pickle the object takes only
493one line of code:
494
495<P>
496<div class="verbatim"><pre>
497pickle.dump(x, f)
498</pre></div>
499
500<P>
501To unpickle the object again, if <code>f</code> is a file object which has
502been opened for reading:
503
504<P>
505<div class="verbatim"><pre>
506x = pickle.load(f)
507</pre></div>
508
509<P>
510(There are other variants of this, used when pickling many objects or
511when you don't want to write the pickled data to a file; consult the
512complete documentation for
513<a class="ulink" href="../lib/module-pickle.html"
514 ><tt class="module">pickle</tt></a> in the
515<em class="citetitle"><a
516 href="../lib/"
517 title="Python Library Reference"
518 >Python Library Reference</a></em>.)
519
520<P>
521<a class="ulink" href="../lib/module-pickle.html"
522 ><tt class="module">pickle</tt></a> is the standard way
523to make Python objects which can be stored and reused by other
524programs or by a future invocation of the same program; the technical
525term for this is a <i class="dfn">persistent</i> object. Because
526<a class="ulink" href="../lib/module-pickle.html"
527 ><tt class="module">pickle</tt></a> is so widely used,
528many authors who write Python extensions take care to ensure that new
529data types such as matrices can be properly pickled and unpickled.
530
531<P>
532
533<DIV CLASS="navigation">
534<div class='online-navigation'>
535<p></p><hr />
536<table align="center" width="100%" cellpadding="0" cellspacing="2">
537<tr>
538<td class='online-navigation'><a rel="prev" title="6. Modules"
539 href="node8.html"><img src='../icons/previous.png'
540 border='0' height='32' alt='Previous Page' width='32' /></A></td>
541<td class='online-navigation'><a rel="parent" title="Python Tutorial"
542 href="tut.html"><img src='../icons/up.png'
543 border='0' height='32' alt='Up One Level' width='32' /></A></td>
544<td class='online-navigation'><a rel="next" title="8. Errors and Exceptions"
545 href="node10.html"><img src='../icons/next.png'
546 border='0' height='32' alt='Next Page' width='32' /></A></td>
547<td align="center" width="100%">Python Tutorial</td>
548<td class='online-navigation'><a rel="contents" title="Table of Contents"
549 href="node2.html"><img src='../icons/contents.png'
550 border='0' height='32' alt='Contents' width='32' /></A></td>
551<td class='online-navigation'><img src='../icons/blank.png'
552 border='0' height='32' alt='' width='32' /></td>
553<td class='online-navigation'><a rel="index" title="Index"
554 href="node19.html"><img src='../icons/index.png'
555 border='0' height='32' alt='Index' width='32' /></A></td>
556</tr></table>
557<div class='online-navigation'>
558<b class="navlabel">Previous:</b>
559<a class="sectref" rel="prev" href="node8.html">6. Modules</A>
560<b class="navlabel">Up:</b>
561<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
562<b class="navlabel">Next:</b>
563<a class="sectref" rel="next" href="node10.html">8. Errors and Exceptions</A>
564</div>
565</div>
566<hr />
567<span class="release-info">Release 2.4.2, documentation updated on 28 September 2005.</span>
568</DIV>
569<!--End of Navigation Panel-->
570<ADDRESS>
571See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
572</ADDRESS>
573</BODY>
574</HTML>