This file is indexed.

/usr/share/doc/diveintopython-zh/html/file_handling/file_objects.html is in diveintopython-zh 5.4b-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
<!DOCTYPE html
  PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   
      <title>6.2.&nbsp;与文件对象共事</title>
      <link rel="stylesheet" href="../diveintopython.css" type="text/css">
      <link rev="made" href="mailto:f8dy@diveintopython.org">
      <meta name="generator" content="DocBook XSL Stylesheets V1.52.2">
      <meta name="keywords" content="Python, Dive Into Python, tutorial, object-oriented, programming, documentation, book, free">
      <meta name="description" content="Python from novice to pro">
      <link rel="home" href="../toc/index.html" title="Dive Into Python">
      <link rel="up" href="index.html" title="第&nbsp;6&nbsp;章&nbsp;异常和文件处理">
      <link rel="previous" href="index.html" title="第&nbsp;6&nbsp;章&nbsp;异常和文件处理">
      <link rel="next" href="for_loops.html" title="6.3.&nbsp;for 循环">
   </head>
   <body>
      <table id="Header" width="100%" border="0" cellpadding="0" cellspacing="0" summary="">
         <tr>
            <td id="breadcrumb" colspan="5" align="left" valign="top">导航:<a href="../index.html">起始页</a>&nbsp;&gt;&nbsp;<a href="../toc/index.html">Dive Into Python</a>&nbsp;&gt;&nbsp;<a href="index.html">异常和文件处理</a>&nbsp;&gt;&nbsp;<span class="thispage">与文件对象共事</span></td>
            <td id="navigation" align="right" valign="top">&nbsp;&nbsp;&nbsp;<a href="index.html" title="上一页: “异常和文件处理”">&lt;&lt;</a>&nbsp;&nbsp;&nbsp;<a href="for_loops.html" title="下一页: “for 循环”">&gt;&gt;</a></td>
         </tr>
         <tr>
            <td colspan="3" id="logocontainer">
               <h1 id="logo"><a href="../index.html" accesskey="1">深入 Python :Dive Into Python 中文版</a></h1>
               <p id="tagline">Python 从新手到专家 [Dip_5.4b_CPyUG_Release]</p>
            </td>
            <td colspan="3" align="right">
               <form id="search" method="GET" action="http://www.google.com/custom">
                  <p><label for="q" accesskey="4">Find:&nbsp;</label><input type="text" id="q" name="q" size="20" maxlength="255" value=""> <input type="submit" value="搜索"><input type="hidden" name="domains" value="woodpecker.org.cn"><input type="hidden" name="sitesearch" value="www.woodpecker.org.cn/diveintopython"></p>
               </form>
            </td>
         </tr>
      </table>
      <!--#include virtual="/inc/ads" -->
      <div class="section" lang="zh_cn">
         <div class="titlepage">
            <div>
               <div>
                  <h2 class="title"><a name="fileinfo.files"></a>6.2.&nbsp;与文件对象共事
                  </h2>
               </div>
            </div>
            <div></div>
         </div>
         <div class="toc">
            <ul>
               <li><span class="section"><a href="file_objects.html#d0e14853">6.2.1. 读取文件</a></span></li>
               <li><span class="section"><a href="file_objects.html#d0e14980">6.2.2. 关闭文件</a></span></li>
               <li><span class="section"><a href="file_objects.html#d0e15107">6.2.3. 处理 I/O 错误</a></span></li>
               <li><span class="section"><a href="file_objects.html#d0e15228">6.2.4. 写入文件</a></span></li>
            </ul>
         </div>
         <div class="abstract">
            <p><span class="application">Python</span> 有一个内置函数,<tt class="function">open</tt>,用来打开在磁盘上的文件。<tt class="function">open</tt> 返回一个文件对象,它拥有一些方法和属性,可以得到被打开文件的信息,以及对被打开文件进行操作。
            </p>
         </div>
         <div class="example"><a name="d0e14781"></a><h3 class="title">&nbsp;6.3.&nbsp;打开文件</h3><pre class="screen"><tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f = open(<span class='pystring'>"/music/_singles/kairo.mp3"</span>, <span class='pystring'>"rb"</span>)</span> <a name="fileinfo.files.1.1"></a><img src="../images/callouts/1.png" alt="1" border="0" width="12" height="12">
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f</span>                                           <a name="fileinfo.files.1.2"></a><img src="../images/callouts/2.png" alt="2" border="0" width="12" height="12">
<span class="computeroutput">&lt;open file '/music/_singles/kairo.mp3', mode 'rb' at 010E3988&gt;</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f.mode</span>                                      <a name="fileinfo.files.1.3"></a><img src="../images/callouts/3.png" alt="3" border="0" width="12" height="12">
<span class="computeroutput">'rb'</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f.name</span>                                      <a name="fileinfo.files.1.4"></a><img src="../images/callouts/4.png" alt="4" border="0" width="12" height="12">
<span class="computeroutput">'/music/_singles/kairo.mp3'</span></pre><div class="calloutlist">
               <table border="0" summary="Callout list">
                  <tr>
                     <td width="12" valign="top" align="left"><a href="#fileinfo.files.1.1"><img src="../images/callouts/1.png" alt="1" border="0" width="12" height="12"></a> 
                     </td>
                     <td valign="top" align="left"><tt class="function">open</tt> 方法可以接收三个参数:文件名、模式和缓冲区参数。只有第一个参数 (文件名) 是必须的;其它两个是<a href="../power_of_introspection/optional_arguments.html" title="4.2.&nbsp;使用可选参数和命名参数">可选的</a>。如果没有指定,文件以文本方式打开。这里我们以二进制方式打开文件进行读取。(<tt class="literal">print open.__doc__</tt> 会给出所有可能模式的很好的解释。)
                     </td>
                  </tr>
                  <tr>
                     <td width="12" valign="top" align="left"><a href="#fileinfo.files.1.2"><img src="../images/callouts/2.png" alt="2" border="0" width="12" height="12"></a> 
                     </td>
                     <td valign="top" align="left"><tt class="function">open</tt> 函数返回一个对象 (到现在为止,<a href="../getting_to_know_python/everything_is_an_object.html" title="2.4.&nbsp;万物皆对象">这一点应该不会使你感到吃惊</a>)。一个文件对象有几个有用的属性。
                     </td>
                  </tr>
                  <tr>
                     <td width="12" valign="top" align="left"><a href="#fileinfo.files.1.3"><img src="../images/callouts/3.png" alt="3" border="0" width="12" height="12"></a> 
                     </td>
                     <td valign="top" align="left">文件对象的 <tt class="varname">mode</tt> 属性告诉你文件以何种模式被打开。
                     </td>
                  </tr>
                  <tr>
                     <td width="12" valign="top" align="left"><a href="#fileinfo.files.1.4"><img src="../images/callouts/4.png" alt="4" border="0" width="12" height="12"></a> 
                     </td>
                     <td valign="top" align="left">文件对象的 <tt class="varname">name</tt> 属性告诉你文件对象所打开的文件名。
                     </td>
                  </tr>
               </table>
            </div>
         </div>
         <div class="section" lang="zh_cn">
            <div class="titlepage">
               <div>
                  <div>
                     <h3 class="title"><a name="d0e14853"></a>6.2.1.&nbsp;读取文件
                     </h3>
                  </div>
               </div>
               <div></div>
            </div>
            <p>你打开文件之后,你要做的第一件事是从中读取,正如下一个例子所展示的。</p>
            <div class="example"><a name="d0e14858"></a><h3 class="title">&nbsp;6.4.&nbsp;读取文件</h3><pre class="screen">
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f</span>
<span class="computeroutput">&lt;open file '/music/_singles/kairo.mp3', mode 'rb' at 010E3988&gt;</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f.tell()</span>              <a name="fileinfo.files.2.1"></a><img src="../images/callouts/1.png" alt="1" border="0" width="12" height="12">
<span class="computeroutput">0</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f.seek(-128, 2)</span>       <a name="fileinfo.files.2.2"></a><img src="../images/callouts/2.png" alt="2" border="0" width="12" height="12">
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f.tell()</span>              <a name="fileinfo.files.2.3"></a><img src="../images/callouts/3.png" alt="3" border="0" width="12" height="12">
<span class="computeroutput">7542909</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">tagData = f.read(128)</span> <a name="fileinfo.files.2.4"></a><img src="../images/callouts/4.png" alt="4" border="0" width="12" height="12">
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">tagData</span>
<span class="computeroutput">'TAGKAIRO****THE BEST GOA         ***DJ MARY-JANE***            
Rave Mix                      2000http://mp3.com/DJMARYJANE     \037'</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f.tell()</span>              <a name="fileinfo.files.2.5"></a><img src="../images/callouts/5.png" alt="5" border="0" width="12" height="12">
<span class="computeroutput">7543037</span></pre><div class="calloutlist">
                  <table border="0" summary="Callout list">
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.2.1"><img src="../images/callouts/1.png" alt="1" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left">一个文件对象维护它所打开文件的状态。文件对象的 <tt class="function">tell</tt> 方法告诉你在被打开文件中的当前位置。因为我们还没有对这个文件做任何事,当前位置为 <tt class="constant">0</tt>,它是文件的起始处。
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.2.2"><img src="../images/callouts/2.png" alt="2" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left">文件对象的 <tt class="function">seek</tt> 方法在被打开文件中移动到另一个位置。第二个参数指出第一个参数是什么意思:<tt class="constant">0</tt> 表示移动到一个绝对位置 (从文件起始处算起),<tt class="constant">1</tt> 表示移到一个相对位置 (从当前位置算起),还有 <tt class="literal">2</tt> 表示相对于文件尾的位置。因为我们搜索的 <span class="abbrev">MP3</span> 标记保存在文件的末尾,我们使用 <tt class="literal">2</tt> 并且告诉文件对象从文件尾移动到 <tt class="literal">128</tt> 字节的位置。
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.2.3"><img src="../images/callouts/3.png" alt="3" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left"><tt class="function">tell</tt> 方法确认了当前位置已经移动了。
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.2.4"><img src="../images/callouts/4.png" alt="4" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left"><tt class="function">read</tt> 方法从被打开文件中读取指定个数的字节,并且返回含有读取数据的字符串。可选参数指定了读取的最大字节数。如果没有指定参数,<tt class="function">read</tt> 将读到文件末尾。(我们本可以在这里简单地说 <tt class="literal">read()</tt> ,因为我们确切地知道在文件的何处,事实上,我们读的是最后 128 个字节。) 读出的数据赋给变量 <tt class="varname">tagData</tt>,并且当前的位置根据所读的字节数作了修改。
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.2.5"><img src="../images/callouts/5.png" alt="5" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left"><tt class="function">tell</tt> 方法确认了当前位置已经移动了。如果做一下算术,你会看到在读了 128 个字节之后,位置数已经增加了 128。
                        </td>
                     </tr>
                  </table>
               </div>
            </div>
         </div>
         <div class="section" lang="zh_cn">
            <div class="titlepage">
               <div>
                  <div>
                     <h3 class="title"><a name="d0e14980"></a>6.2.2.&nbsp;关闭文件
                     </h3>
                  </div>
               </div>
               <div></div>
            </div>
            <p>打开文件消耗系统资源,并且其间其它程序可能无法访问它们 (取决于文件模式)。这就是一旦操作完毕就该关闭文件的重要所在。</p>
            <div class="example"><a name="d0e14985"></a><h3 class="title">&nbsp;6.5.&nbsp;关闭文件</h3><pre class="screen">
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f</span>
<span class="computeroutput">&lt;open file '/music/_singles/kairo.mp3', mode 'rb' at 010E3988&gt;</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f.closed</span>       <a name="fileinfo.files.3.1"></a><img src="../images/callouts/1.png" alt="1" border="0" width="12" height="12">
<span class="computeroutput">False</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f.close()</span>      <a name="fileinfo.files.3.2"></a><img src="../images/callouts/2.png" alt="2" border="0" width="12" height="12">
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f</span>
<span class="computeroutput">&lt;closed file '/music/_singles/kairo.mp3', mode 'rb' at 010E3988&gt;</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f.closed</span>       <a name="fileinfo.files.3.3"></a><img src="../images/callouts/3.png" alt="3" border="0" width="12" height="12">
<span class="computeroutput">True</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f.seek(0)</span>      <a name="fileinfo.files.3.4"></a><img src="../images/callouts/4.png" alt="4" border="0" width="12" height="12">
<span class="traceback">Traceback (innermost last):
  File "&lt;interactive input&gt;", line 1, in ?
ValueError: I/O operation on closed file</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f.tell()</span>
<span class="traceback">Traceback (innermost last):
  File "&lt;interactive input&gt;", line 1, in ?
ValueError: I/O operation on closed file</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f.read()</span>
<span class="traceback">Traceback (innermost last):
  File "&lt;interactive input&gt;", line 1, in ?
ValueError: I/O operation on closed file</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">f.close()</span>      <a name="fileinfo.files.3.5"></a><img src="../images/callouts/5.png" alt="5" border="0" width="12" height="12"></pre><div class="calloutlist">
                  <table border="0" summary="Callout list">
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.3.1"><img src="../images/callouts/1.png" alt="1" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left">文件对象的 <tt class="varname">closed</tt> 属性表示对象是打开还是关闭了文件。在本例中,文件仍然打开着 (<tt class="varname">closed</tt><tt class="constant">False</tt>)。
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.3.2"><img src="../images/callouts/2.png" alt="2" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left">为了关闭文件,调用文件对象的 <tt class="function">close</tt> 方法。这样就释放掉你加在文件上的锁 (如果有的话),刷新被缓冲的系统还未写入的输出 (如果有的话),并且释放系统资源。
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.3.3"><img src="../images/callouts/3.png" alt="3" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left"><tt class="varname">closed</tt> 属性证实了文件被关闭了。
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.3.4"><img src="../images/callouts/4.png" alt="4" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left">文件被关闭了,但这并不意味着文件对象不再存在。变量 <tt class="varname">f</tt> 将继续存在,直到它<a href="../object_oriented_framework/instantiating_classes.html#fileinfo.scope" title="例&nbsp;5.8.&nbsp;尝试实现内存泄漏">超出作用域</a>或被手工删除。然而,一旦文件被关闭,操作它的方法就没有一个能使用;它们都会引发异常。
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.3.5"><img src="../images/callouts/5.png" alt="5" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left">对一个文件已经关闭的文件对象调用 <tt class="function">close</tt> <span class="emphasis"><em>不会</em></span> 引发异常,它静静地失败。
                        </td>
                     </tr>
                  </table>
               </div>
            </div>
         </div>
         <div class="section" lang="zh_cn">
            <div class="titlepage">
               <div>
                  <div>
                     <h3 class="title"><a name="d0e15107"></a>6.2.3.&nbsp;处理 <span class="acronym">I/O</span> 错误
                     </h3>
                  </div>
               </div>
               <div></div>
            </div>
            <p>现在你已经足能理解前一章的例子程序 <tt class="filename">fileinfo.py</tt> 的文件处理代码了。下面这个例子展示了如何安全地打开文件和读取文件,以及优美地处理错误。
            </p>
            <div class="example"><a name="fileinfo.files.incode"></a><h3 class="title">&nbsp;6.6.&nbsp;<tt class="classname">MP3FileInfo</tt> 中的文件对象
               </h3><pre class="programlisting">
        <span class='pykeyword'>try</span>:                                <a name="fileinfo.files.4.1"></a><img src="../images/callouts/1.png" alt="1" border="0" width="12" height="12">
            fsock = open(filename, <span class='pystring'>"rb"</span>, 0) <a name="fileinfo.files.4.2"></a><img src="../images/callouts/2.png" alt="2" border="0" width="12" height="12">
            <span class='pykeyword'>try</span>:                           
                fsock.seek(-128, 2)         <a name="fileinfo.files.4.3"></a><img src="../images/callouts/3.png" alt="3" border="0" width="12" height="12">
                tagdata = fsock.read(128)   <a name="fileinfo.files.4.4"></a><img src="../images/callouts/4.png" alt="4" border="0" width="12" height="12">
            <span class='pykeyword'>finally</span>:                        <a name="fileinfo.files.4.5"></a><img src="../images/callouts/5.png" alt="5" border="0" width="12" height="12">
                fsock.close()              
            .
            .
            .
        <span class='pykeyword'>except</span> IOError:                     <a name="fileinfo.files.4.6"></a><img src="../images/callouts/6.png" alt="6" border="0" width="12" height="12">
            <span class='pykeyword'>pass</span>                           </pre><div class="calloutlist">
                  <table border="0" summary="Callout list">
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.4.1"><img src="../images/callouts/1.png" alt="1" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left">因为打开和读取文件有风险,并且可能引发异常,所有这些代码都用一个 <tt class="literal">try...except</tt> 块封装。(嘿,<a href="../getting_to_know_python/indenting_code.html" title="2.5.&nbsp;代码缩进">标准化的缩近</a>不好吗?这就是你开始欣赏它的地方。)
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.4.2"><img src="../images/callouts/2.png" alt="2" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left"><tt class="function">open</tt> 函数可能引发 <tt class="errorcode">IOError</tt> 异常。(可能是文件不存在。)
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.4.3"><img src="../images/callouts/3.png" alt="3" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left"><tt class="function">seek</tt> 方法可能引发 <tt class="errorcode">IOError</tt> 异常。(可能是文件长度小于 128 字节。)
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.4.4"><img src="../images/callouts/4.png" alt="4" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left"><tt class="function">read</tt> 方法可能引发 <tt class="errorcode">IOError</tt> 异常。(可能磁盘有坏扇区,或它在一个网络驱动器上,而网络刚好断了。)
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.4.5"><img src="../images/callouts/5.png" alt="5" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left">这是新的:一个 <tt class="literal">try...finally</tt> 块。一旦文件通过 <tt class="function">open</tt> 函数被成功地打开,我们应该绝对保证把它关闭,即使是在 <tt class="function">seek</tt><tt class="function">read</tt> 方法引发了一个异常时。<tt class="literal">try...finally</tt> 块可以用来:在 <tt class="literal">finally</tt> 块中的代码将<span class="emphasis"><em>总是</em></span> 被执行,甚至某些东西在 <tt class="literal">try</tt> 块中引发一个异常也会执行。可以这样考虑,不管在路上发生什么,代码都会被 “即将灭亡” 地执行。
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.4.6"><img src="../images/callouts/6.png" alt="6" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left">最后,处理我们的 <tt class="errorcode">IOError</tt> 异常。它可能是由调用 <tt class="function">open</tt><tt class="function">seek</tt><tt class="function">read</tt> 引发的 <tt class="errorcode">IOError</tt> 异常。这里,我们其实不用关心,因为将要做的事就是静静地忽略它然后继续。(记住,<tt class="literal">pass</tt> 是一条不做任何事的 <span class="application">Python</span> 语句。) 这样完全合法,“<span class="quote">处理</span>” 一个异常可以明确表示不做任何事。它仍然被认为处理过了,并且处理将正常继续,从 <tt class="literal">try...except</tt> 块的下一行代码开始。
                        </td>
                     </tr>
                  </table>
               </div>
            </div>
         </div>
         <div class="section" lang="zh_cn">
            <div class="titlepage">
               <div>
                  <div>
                     <h3 class="title"><a name="d0e15228"></a>6.2.4.&nbsp;写入文件
                     </h3>
                  </div>
               </div>
               <div></div>
            </div>
            <p>正如你所期待的,你也能用与读取文件同样的方式写入文件。有两种基本的文件模式:</p>
            <div class="itemizedlist">
               <ul>
                  <li>追加 (Append) 模式将数据追加到文件尾。</li>
                  <li>写入 (write) 模式将覆盖文件的原有内容。</li>
               </ul>
            </div>
            <p>如果文件还不存在,任意一种模式都将自动创建文件,因此从来不需要任何复杂的逻辑:“如果 log 文件还不存在,将创建一个新的空文件,正因为如此,你可以第一次就打开它”。打开文件并开始写就可以了。</p>
            <div class="example"><a name="fileinfo.files.writeandappend"></a><h3 class="title">&nbsp;6.7.&nbsp;写入文件</h3><pre class="screen">
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">logfile = open(<span class='pystring'>'test.log'</span>, <span class='pystring'>'w'</span>)</span> <a name="fileinfo.files.5.1"></a><img src="../images/callouts/1.png" alt="1" border="0" width="12" height="12">
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">logfile.write(<span class='pystring'>'test succeeded'</span>)</span> <a name="fileinfo.files.5.2"></a><img src="../images/callouts/2.png" alt="2" border="0" width="12" height="12">
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">logfile.close()</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput"><span class='pykeyword'>print</span> file(<span class='pystring'>'test.log'</span>).read()</span>   <a name="fileinfo.files.5.3"></a><img src="../images/callouts/3.png" alt="3" border="0" width="12" height="12">
<span class="computeroutput">test succeeded</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">logfile = open(<span class='pystring'>'test.log'</span>, <span class='pystring'>'a'</span>)</span> <a name="fileinfo.files.5.4"></a><img src="../images/callouts/4.png" alt="4" border="0" width="12" height="12">
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">logfile.write(<span class='pystring'>'line 2'</span>)</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput">logfile.close()</span>
<tt class="prompt">&gt;&gt;&gt; </tt><span class="userinput"><span class='pykeyword'>print</span> file(<span class='pystring'>'test.log'</span>).read()</span>   <a name="fileinfo.files.5.5"></a><img src="../images/callouts/5.png" alt="5" border="0" width="12" height="12">
<span class="computeroutput">test succeededline 2</span>
</pre><div class="calloutlist">
                  <table border="0" summary="Callout list">
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.5.1"><img src="../images/callouts/1.png" alt="1" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left">你可以大胆地开始创建新文件 <tt class="filename">test.log</tt> 或覆盖现有文件,并为写入目的而打开它。(第二个参数 <tt class="literal">"w"</tt> 的意思是为文件写入而打开。) 是的,它和想象中的一样危险。我希望你不要关心文件以前的内容,因为它现在已经不存在了。
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.5.2"><img src="../images/callouts/2.png" alt="2" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left">你可以使用 <tt class="function">open</tt> 返回的文件对象的 <tt class="function">write</tt> 方法向一个新打开的文件添加数据。
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.5.3"><img src="../images/callouts/3.png" alt="3" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left"><tt class="function">file</tt><tt class="function">open</tt> 的同义语。这一行语句打开文件,读取内容,并打印它们。
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.5.4"><img src="../images/callouts/4.png" alt="4" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left">碰巧你知道 <tt class="filename">test.log</tt> 存在 (因为你刚向它写完了数据),所以你可以打开它并向其追加数据。(<tt class="literal">"a"</tt> 参数的意思是为追加目的打开文件。) 实际上即使文件不存在你也可以这样做,因为以追加方式打开一文件时,如果需要的话会创建文件。但是追加操作<span class="emphasis"><em>从不</em></span> 损坏文件的现有内容。
                        </td>
                     </tr>
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo.files.5.5"><img src="../images/callouts/5.png" alt="5" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left">正如你所看到的,原来的行和你以追加方式写入的第二行现在都在 <tt class="filename">test.log</tt> 中了。同时注意两行之间并没包含回车符。因为两次写入文件时都没有明确地写入回车符,所以文件中没有包含回车符。你可以用 <tt class="literal">"\n"</tt> 写入回车符。因为你没做这项工作,所以你写到文件的所有内容都将显示在同一行上。
                        </td>
                     </tr>
                  </table>
               </div>
            </div>
            <div class="furtherreading">
               <h3>进一步阅读</h3>
               <ul>
                  <li><a href="http://www.python.org/doc/current/tut/tut.html"><i class="citetitle"><span class="application">Python</span> Tutorial</i></a> 讨论了文件的读取和写入,包括如何<a href="http://www.python.org/doc/current/tut/node9.html#SECTION009210000000000000000">将一个文件一次一行地读到 list 中</a></li>
                  <li><a href="http://www.effbot.org/guides/">eff-bot</a> 讨论了<a href="http://www.effbot.org/guides/readline-performance.htm">各种各样读取文件方法</a> 的效率和性能。
                  </li>
                  <li><a href="http://www.faqts.com/knowledge-base/index.phtml/fid/199/"><span class="application">Python</span> Knowledge Base</a> 回答了<a href="http://www.faqts.com/knowledge-base/index.phtml/fid/552">关于文件的常见问题</a></li>
                  <li><a href="http://www.python.org/doc/current/lib/"><i class="citetitle"><span class="application">Python</span> Library Reference</i></a> 总结了<a href="http://www.python.org/doc/current/lib/bltin-file-objects.html">所有文件对象模块</a></li>
               </ul>
            </div>
         </div>
      </div>
      <table class="Footer" width="100%" border="0" cellpadding="0" cellspacing="0" summary="">
         <tr>
            <td width="35%" align="left"><br><a class="NavigationArrow" href="index.html">&lt;&lt;&nbsp;异常和文件处理</a></td>
            <td width="30%" align="center"><br>&nbsp;<span class="divider">|</span>&nbsp;<a href="index.html#fileinfo.exception" title="6.1.&nbsp;异常处理">1</a> <span class="divider">|</span> <span class="thispage">2</span> <span class="divider">|</span> <a href="for_loops.html" title="6.3.&nbsp;for 循环">3</a> <span class="divider">|</span> <a href="more_on_modules.html" title="6.4.&nbsp;使用 sys.modules">4</a> <span class="divider">|</span> <a href="os_module.html" title="6.5.&nbsp;与目录共事">5</a> <span class="divider">|</span> <a href="all_together.html" title="6.6.&nbsp;全部放在一起">6</a> <span class="divider">|</span> <a href="summary.html" title="6.7.&nbsp;小结">7</a>&nbsp;<span class="divider">|</span>&nbsp;
            </td>
            <td width="35%" align="right"><br><a class="NavigationArrow" href="for_loops.html">for 循环&nbsp;&gt;&gt;</a></td>
         </tr>
         <tr>
            <td colspan="3"><br></td>
         </tr>
      </table>
      <div class="Footer">
         <p class="copyright">Copyright © 2000, 2001, 2002, 2003, 2004 <a href="mailto:mark@diveintopython.org">Mark Pilgrim</a></p>
         <p class="copyright">Copyright © 2001, 2002, 2003, 2004, 2005, 2006, 2007 <a href="mailto:python-cn@googlegroups.com">CPyUG (邮件列表)</a></p>
      </div>
   </body>
</html>