Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / amd64 / html / python / tut / node9.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<link rel="STYLESHEET" href="tut.css" type='text/css' />
<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
<link rel='start' href='../index.html' title='Python Documentation Index' />
<link rel="first" href="tut.html" title='Python Tutorial' />
<link rel='contents' href='node2.html' title="Contents" />
<link rel='index' href='node19.html' title='Index' />
<link rel='last' href='about.html' title='About this document...' />
<link rel='help' href='about.html' title='About this document...' />
<link rel="next" href="node10.html" />
<link rel="prev" href="node8.html" />
<link rel="parent" href="tut.html" />
<link rel="next" href="node10.html" />
<meta name='aesop' content='information' />
<title>7. Input and Output </title>
</head>
<body>
<DIV CLASS="navigation">
<div id='top-navigation-panel' xml:id='top-navigation-panel'>
<table align="center" width="100%" cellpadding="0" cellspacing="2">
<tr>
<td class='online-navigation'><a rel="prev" title="6. Modules"
href="node8.html"><img src='../icons/previous.png'
border='0' height='32' alt='Previous Page' width='32' /></A></td>
<td class='online-navigation'><a rel="parent" title="Python Tutorial"
href="tut.html"><img src='../icons/up.png'
border='0' height='32' alt='Up One Level' width='32' /></A></td>
<td class='online-navigation'><a rel="next" title="8. Errors and Exceptions"
href="node10.html"><img src='../icons/next.png'
border='0' height='32' alt='Next Page' width='32' /></A></td>
<td align="center" width="100%">Python Tutorial</td>
<td class='online-navigation'><a rel="contents" title="Table of Contents"
href="node2.html"><img src='../icons/contents.png'
border='0' height='32' alt='Contents' width='32' /></A></td>
<td class='online-navigation'><img src='../icons/blank.png'
border='0' height='32' alt='' width='32' /></td>
<td class='online-navigation'><a rel="index" title="Index"
href="node19.html"><img src='../icons/index.png'
border='0' height='32' alt='Index' width='32' /></A></td>
</tr></table>
<div class='online-navigation'>
<b class="navlabel">Previous:</b>
<a class="sectref" rel="prev" href="node8.html">6. Modules</A>
<b class="navlabel">Up:</b>
<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
<b class="navlabel">Next:</b>
<a class="sectref" rel="next" href="node10.html">8. Errors and Exceptions</A>
</div>
<hr /></div>
</DIV>
<!--End of Navigation Panel-->
<div class='online-navigation'>
<!--Table of Child-Links-->
<A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a>
<UL CLASS="ChildLinks">
<LI><A href="node9.html#SECTION009100000000000000000">7.1 Fancier Output Formatting</a>
<LI><A href="node9.html#SECTION009200000000000000000">7.2 Reading and Writing Files</a>
<UL>
<LI><A href="node9.html#SECTION009210000000000000000">7.2.1 Methods of File Objects</a>
<LI><A href="node9.html#SECTION009220000000000000000">7.2.2 The <tt class="module">pickle</tt> Module</a>
</ul></ul>
<!--End of Table of Child-Links-->
</div>
<HR>
<H1><A NAME="SECTION009000000000000000000"></A><A NAME="io"></A>
<BR>
7. Input and Output
</H1>
<P>
There are several ways to present the output of a program; data can be
printed in a human-readable form, or written to a file for future use.
This chapter will discuss some of the possibilities.
<P>
<H1><A NAME="SECTION009100000000000000000"></A><A NAME="formatting"></A>
<BR>
7.1 Fancier Output Formatting
</H1>
<P>
So far we've encountered two ways of writing values: <em>expression
statements</em> and the <tt class="keyword">print</tt> statement. (A third way is using
the <tt class="method">write()</tt> method of file objects; the standard output file
can be referenced as <code>sys.stdout</code>. See the Library Reference for
more information on this.)
<P>
Often you'll want more control over the formatting of your output than
simply printing space-separated values. There are two ways to format
your output; the first way is to do all the string handling yourself;
using string slicing and concatenation operations you can create any
layout you can imagine. The standard module
<tt class="module">string</tt><a id='l2h-29' xml:id='l2h-29'></a> contains some useful operations
for padding strings to a given column width; these will be discussed
shortly. The second way is to use the <code>%</code> operator with a
string as the left argument. The <code>%</code> operator interprets the
left argument much like a <tt class="cfunction">sprintf()</tt>-style format
string to be applied to the right argument, and returns the string
resulting from this formatting operation.
<P>
One question remains, of course: how do you convert values to strings?
Luckily, Python has ways to convert any value to a string: pass it to
the <tt class="function">repr()</tt> or <tt class="function">str()</tt> functions. Reverse quotes
(<code>``</code>) are equivalent to <tt class="function">repr()</tt>, but they are no
longer used in modern Python code and will likely not be in future
versions of the language.
<P>
The <tt class="function">str()</tt> function is meant to return representations of
values which are fairly human-readable, while <tt class="function">repr()</tt> is
meant to generate representations which can be read by the interpreter
(or will force a <tt class="exception">SyntaxError</tt> if there is not equivalent
syntax). For objects which don't have a particular representation for
human consumption, <tt class="function">str()</tt> will return the same value as
<tt class="function">repr()</tt>. Many values, such as numbers or structures like
lists and dictionaries, have the same representation using either
function. Strings and floating point numbers, in particular, have two
distinct representations.
<P>
Some examples:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; s = 'Hello, world.'
&gt;&gt;&gt; str(s)
'Hello, world.'
&gt;&gt;&gt; repr(s)
"'Hello, world.'"
&gt;&gt;&gt; str(0.1)
'0.1'
&gt;&gt;&gt; repr(0.1)
'0.10000000000000001'
&gt;&gt;&gt; x = 10 * 3.25
&gt;&gt;&gt; y = 200 * 200
&gt;&gt;&gt; s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
&gt;&gt;&gt; print s
The value of x is 32.5, and y is 40000...
&gt;&gt;&gt; # The repr() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
&gt;&gt;&gt; hellos = repr(hello)
&gt;&gt;&gt; print hellos
'hello, world\n'
&gt;&gt;&gt; # The argument to repr() may be any Python object:
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"
&gt;&gt;&gt; # reverse quotes are convenient in interactive sessions:
... `x, y, ('spam', 'eggs')`
"(32.5, 40000, ('spam', 'eggs'))"
</pre></div>
<P>
Here are two ways to write a table of squares and cubes:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; for x in range(1, 11):
... print repr(x).rjust(2), repr(x*x).rjust(3),
... # Note trailing comma on previous line
... print repr(x*x*x).rjust(4)
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
&gt;&gt;&gt; for x in range(1,11):
... print '%2d %3d %4d' % (x, x*x, x*x*x)
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
</pre></div>
<P>
(Note that one space between each column was added by the way
<tt class="keyword">print</tt> works: it always adds spaces between its arguments.)
<P>
This example demonstrates the <tt class="method">rjust()</tt> method of string objects,
which right-justifies a string in a field of a given width by padding
it with spaces on the left. There are similar methods
<tt class="method">ljust()</tt> and <tt class="method">center()</tt>. These
methods do not write anything, they just return a new string. If
the input string is too long, they don't truncate it, but return it
unchanged; this will mess up your column lay-out but that's usually
better than the alternative, which would be lying about a value. (If
you really want truncation you can always add a slice operation, as in
"<tt class="samp">x.ljust(n)[:n]</tt>".)
<P>
There is another method, <tt class="method">zfill()</tt>, which pads a
numeric string on the left with zeros. It understands about plus and
minus signs:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; '12'.zfill(5)
'00012'
&gt;&gt;&gt; '-3.14'.zfill(7)
'-003.14'
&gt;&gt;&gt; '3.14159265359'.zfill(5)
'3.14159265359'
</pre></div>
<P>
Using the <code>%</code> operator looks like this:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; import math
&gt;&gt;&gt; print 'The value of PI is approximately %5.3f.' % math.pi
The value of PI is approximately 3.142.
</pre></div>
<P>
If there is more than one format in the string, you need to pass a
tuple as right operand, as in this example:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
&gt;&gt;&gt; for name, phone in table.items():
... print '%-10s ==&gt; %10d' % (name, phone)
...
Jack ==&gt; 4098
Dcab ==&gt; 7678
Sjoerd ==&gt; 4127
</pre></div>
<P>
Most formats work exactly as in C and require that you pass the proper
type; however, if you don't you get an exception, not a core dump.
The <code>%s</code> format is more relaxed: if the corresponding argument is
not a string object, it is converted to string using the
<tt class="function">str()</tt> built-in function. Using <code>*</code> to pass the width
or precision in as a separate (integer) argument is supported. The
C formats <code>%n</code> and <code>%p</code> are not supported.
<P>
If you have a really long format string that you don't want to split
up, it would be nice if you could reference the variables to be
formatted by name instead of by position. This can be done by using
form <code>%(name)format</code>, as shown here:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
&gt;&gt;&gt; print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
</pre></div>
<P>
This is particularly useful in combination with the new built-in
<tt class="function">vars()</tt> function, which returns a dictionary containing all
local variables.
<P>
<H1><A NAME="SECTION009200000000000000000"></A><A NAME="files"></A>
<BR>
7.2 Reading and Writing Files
</H1>
<P>
<tt class="function">open()</tt><a id='l2h-30' xml:id='l2h-30'></a> returns a file
object<a id='l2h-31' xml:id='l2h-31'></a>, and is most commonly used with two arguments:
"<tt class="samp">open(<var>filename</var>, <var>mode</var>)</tt>".
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; f=open('/tmp/workfile', 'w')
&gt;&gt;&gt; print f
&lt;open file '/tmp/workfile', mode 'w' at 80a0960&gt;
</pre></div>
<P>
The first argument is a string containing the filename. The second
argument is another string containing a few characters describing the
way in which the file will be used. <var>mode</var> can be <code>'r'</code> when
the file will only be read, <code>'w'</code> for only writing (an existing
file with the same name will be erased), and <code>'a'</code> opens the file
for appending; any data written to the file is automatically added to
the end. <code>'r+'</code> opens the file for both reading and writing.
The <var>mode</var> argument is optional; <code>'r'</code> will be assumed if
it's omitted.
<P>
On Windows and the Macintosh, <code>'b'</code> appended to the
mode opens the file in binary mode, so there are also modes like
<code>'rb'</code>, <code>'wb'</code>, and <code>'r+b'</code>. Windows makes a
distinction between text and binary files; the end-of-line characters
in text files are automatically altered slightly when data is read or
written. This behind-the-scenes modification to file data is fine for
ASCII text files, but it'll corrupt binary data like that in <span class="file">JPEG</span> or
<span class="file">EXE</span> files. Be very careful to use binary mode when reading and
writing such files.
<P>
<H2><A NAME="SECTION009210000000000000000"></A><A NAME="fileMethods"></A>
<BR>
7.2.1 Methods of File Objects
</H2>
<P>
The rest of the examples in this section will assume that a file
object called <code>f</code> has already been created.
<P>
To read a file's contents, call <code>f.read(<var>size</var>)</code>, which reads
some quantity of data and returns it as a string. <var>size</var> is an
optional numeric argument. When <var>size</var> is omitted or negative,
the entire contents of the file will be read and returned; it's your
problem if the file is twice as large as your machine's memory.
Otherwise, at most <var>size</var> bytes are read and returned. If the end
of the file has been reached, <code>f.read()</code> will return an empty
string (<code>""</code>).
<div class="verbatim"><pre>
&gt;&gt;&gt; f.read()
'This is the entire file.\n'
&gt;&gt;&gt; f.read()
''
</pre></div>
<P>
<code>f.readline()</code> reads a single line from the file; a newline
character (<code>&#92;n</code>) is left at the end of the string, and is only
omitted on the last line of the file if the file doesn't end in a
newline. This makes the return value unambiguous; if
<code>f.readline()</code> returns an empty string, the end of the file has
been reached, while a blank line is represented by <code>'&#92;n'</code>, a
string containing only a single newline.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; f.readline()
'This is the first line of the file.\n'
&gt;&gt;&gt; f.readline()
'Second line of the file\n'
&gt;&gt;&gt; f.readline()
''
</pre></div>
<P>
<code>f.readlines()</code> returns a list containing all the lines of data
in the file. If given an optional parameter <var>sizehint</var>, it reads
that many bytes from the file and enough more to complete a line, and
returns the lines from that. This is often used to allow efficient
reading of a large file by lines, but without having to load the
entire file in memory. Only complete lines will be returned.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; f.readlines()
['This is the first line of the file.\n', 'Second line of the file\n']
</pre></div>
<P>
An alternate approach to reading lines is to loop over the file object.
This is memory efficient, fast, and leads to simpler code:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; for line in f:
print line,
This is the first line of the file.
Second line of the file
</pre></div>
<P>
The alternative approach is simpler but does not provide as fine-grained
control. Since the two approaches manage line buffering differently,
they should not be mixed.
<P>
<code>f.write(<var>string</var>)</code> writes the contents of <var>string</var> to
the file, returning <code>None</code>.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; f.write('This is a test\n')
</pre></div>
<P>
To write something other than a string, it needs to be converted to a
string first:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; value = ('the answer', 42)
&gt;&gt;&gt; s = str(value)
&gt;&gt;&gt; f.write(s)
</pre></div>
<P>
<code>f.tell()</code> returns an integer giving the file object's current
position in the file, measured in bytes from the beginning of the
file. To change the file object's position, use
"<tt class="samp">f.seek(<var>offset</var>, <var>from_what</var>)</tt>". The position is
computed from adding <var>offset</var> to a reference point; the reference
point is selected by the <var>from_what</var> argument. A
<var>from_what</var> value of 0 measures from the beginning of the file, 1
uses the current file position, and 2 uses the end of the file as the
reference point. <var>from_what</var> can be omitted and defaults to 0,
using the beginning of the file as the reference point.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; f = open('/tmp/workfile', 'r+')
&gt;&gt;&gt; f.write('0123456789abcdef')
&gt;&gt;&gt; f.seek(5) # Go to the 6th byte in the file
&gt;&gt;&gt; f.read(1)
'5'
&gt;&gt;&gt; f.seek(-3, 2) # Go to the 3rd byte before the end
&gt;&gt;&gt; f.read(1)
'd'
</pre></div>
<P>
When you're done with a file, call <code>f.close()</code> to close it and
free up any system resources taken up by the open file. After calling
<code>f.close()</code>, attempts to use the file object will automatically fail.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; f.close()
&gt;&gt;&gt; f.read()
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in ?
ValueError: I/O operation on closed file
</pre></div>
<P>
File objects have some additional methods, such as
<tt class="method">isatty()</tt> and <tt class="method">truncate()</tt> which are less frequently
used; consult the Library Reference for a complete guide to file
objects.
<P>
<H2><A NAME="SECTION009220000000000000000"></A><A NAME="pickle"></A>
<BR>
7.2.2 The <tt class="module">pickle</tt> Module
</H2>
<a id='l2h-32' xml:id='l2h-32'></a>
<P>
Strings can easily be written to and read from a file. Numbers take a
bit more effort, since the <tt class="method">read()</tt> method only returns
strings, which will have to be passed to a function like
<tt class="function">int()</tt>, which takes a string like <code>'123'</code> and
returns its numeric value 123. However, when you want to save more
complex data types like lists, dictionaries, or class instances,
things get a lot more complicated.
<P>
Rather than have users be constantly writing and debugging code to
save complicated data types, Python provides a standard module called
<a class="ulink" href="../lib/module-pickle.html"
><tt class="module">pickle</tt></a>. This is an
amazing module that can take almost
any Python object (even some forms of Python code!), and convert it to
a string representation; this process is called <i class="dfn">pickling</i>.
Reconstructing the object from the string representation is called
<i class="dfn">unpickling</i>. Between pickling and unpickling, the string
representing the object may have been stored in a file or data, or
sent over a network connection to some distant machine.
<P>
If you have an object <code>x</code>, and a file object <code>f</code> that's been
opened for writing, the simplest way to pickle the object takes only
one line of code:
<P>
<div class="verbatim"><pre>
pickle.dump(x, f)
</pre></div>
<P>
To unpickle the object again, if <code>f</code> is a file object which has
been opened for reading:
<P>
<div class="verbatim"><pre>
x = pickle.load(f)
</pre></div>
<P>
(There are other variants of this, used when pickling many objects or
when you don't want to write the pickled data to a file; consult the
complete documentation for
<a class="ulink" href="../lib/module-pickle.html"
><tt class="module">pickle</tt></a> in the
<em class="citetitle"><a
href="../lib/"
title="Python Library Reference"
>Python Library Reference</a></em>.)
<P>
<a class="ulink" href="../lib/module-pickle.html"
><tt class="module">pickle</tt></a> is the standard way
to make Python objects which can be stored and reused by other
programs or by a future invocation of the same program; the technical
term for this is a <i class="dfn">persistent</i> object. Because
<a class="ulink" href="../lib/module-pickle.html"
><tt class="module">pickle</tt></a> is so widely used,
many authors who write Python extensions take care to ensure that new
data types such as matrices can be properly pickled and unpickled.
<P>
<DIV CLASS="navigation">
<div class='online-navigation'>
<p></p><hr />
<table align="center" width="100%" cellpadding="0" cellspacing="2">
<tr>
<td class='online-navigation'><a rel="prev" title="6. Modules"
href="node8.html"><img src='../icons/previous.png'
border='0' height='32' alt='Previous Page' width='32' /></A></td>
<td class='online-navigation'><a rel="parent" title="Python Tutorial"
href="tut.html"><img src='../icons/up.png'
border='0' height='32' alt='Up One Level' width='32' /></A></td>
<td class='online-navigation'><a rel="next" title="8. Errors and Exceptions"
href="node10.html"><img src='../icons/next.png'
border='0' height='32' alt='Next Page' width='32' /></A></td>
<td align="center" width="100%">Python Tutorial</td>
<td class='online-navigation'><a rel="contents" title="Table of Contents"
href="node2.html"><img src='../icons/contents.png'
border='0' height='32' alt='Contents' width='32' /></A></td>
<td class='online-navigation'><img src='../icons/blank.png'
border='0' height='32' alt='' width='32' /></td>
<td class='online-navigation'><a rel="index" title="Index"
href="node19.html"><img src='../icons/index.png'
border='0' height='32' alt='Index' width='32' /></A></td>
</tr></table>
<div class='online-navigation'>
<b class="navlabel">Previous:</b>
<a class="sectref" rel="prev" href="node8.html">6. Modules</A>
<b class="navlabel">Up:</b>
<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
<b class="navlabel">Next:</b>
<a class="sectref" rel="next" href="node10.html">8. Errors and Exceptions</A>
</div>
</div>
<hr />
<span class="release-info">Release 2.4.2, documentation updated on 28 September 2005.</span>
</DIV>
<!--End of Navigation Panel-->
<ADDRESS>
See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
</ADDRESS>
</BODY>
</HTML>