-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodecs.html
More file actions
1939 lines (1864 loc) · 131 KB
/
codecs.html
File metadata and controls
1939 lines (1864 loc) · 131 KB
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_TW">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>7.2. codecs — Codec registry and base classes — Python 3.7.0 說明文件</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/translations.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="在 Python 3.7.0 說明文件 中搜尋"
href="../_static/opensearch.xml"/>
<link rel="author" title="關於這些文件" href="../about.html" />
<link rel="index" title="索引" href="../genindex.html" />
<link rel="search" title="搜尋" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="8. Data Types" href="datatypes.html" />
<link rel="prev" title="7.1. struct — Interpret bytes as packed binary data" href="struct.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/library/codecs.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<h3>瀏覽</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模組索引"
>模組</a> |</li>
<li class="right" >
<a href="datatypes.html" title="8. Data Types"
accesskey="N">下一頁</a> |</li>
<li class="right" >
<a href="struct.html" title="7.1. struct — Interpret bytes as packed binary data"
accesskey="P">上一頁</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> »</li>
<li>
<span class="language_switcher_placeholder">zh_TW</span>
<span class="version_switcher_placeholder">3.7.0</span>
<a href="../index.html">Documentation </a> »
</li>
<li class="nav-item nav-item-1"><a href="index.html" >Python 標準函式庫 (Standard Library)</a> »</li>
<li class="nav-item nav-item-2"><a href="binary.html" accesskey="U">7. Binary Data Services</a> »</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="module-codecs">
<span id="codecs-codec-registry-and-base-classes"></span><h1>7.2. <a class="reference internal" href="#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> — Codec registry and base classes<a class="headerlink" href="#module-codecs" title="本標題的永久連結">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.7/Lib/codecs.py">Lib/codecs.py</a></p>
<hr class="docutils" id="index-0" />
<p>This module defines base classes for standard Python codecs (encoders and
decoders) and provides access to the internal Python codec registry, which
manages the codec and error handling lookup process. Most standard codecs
are <a class="reference internal" href="../glossary.html#term-text-encoding"><span class="xref std std-term">text encodings</span></a>, which encode text to bytes,
but there are also codecs provided that encode text to text, and bytes to
bytes. Custom codecs may encode and decode between arbitrary types, but some
module features are restricted to use specifically with
<a class="reference internal" href="../glossary.html#term-text-encoding"><span class="xref std std-term">text encodings</span></a>, or with codecs that encode to
<a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>.</p>
<p>The module defines the following functions for encoding and decoding with
any codec:</p>
<dl class="function">
<dt id="codecs.encode">
<code class="descclassname">codecs.</code><code class="descname">encode</code><span class="sig-paren">(</span><em>obj</em>, <em>encoding='utf-8'</em>, <em>errors='strict'</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.encode" title="本定義的永久連結">¶</a></dt>
<dd><p>Encodes <em>obj</em> using the codec registered for <em>encoding</em>.</p>
<p><em>Errors</em> may be given to set the desired error handling scheme. The
default error handler is <code class="docutils literal notranslate"><span class="pre">'strict'</span></code> meaning that encoding errors raise
<a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> (or a more codec specific subclass, such as
<a class="reference internal" href="exceptions.html#UnicodeEncodeError" title="UnicodeEncodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code></a>). Refer to <a class="reference internal" href="#codec-base-classes"><span class="std std-ref">Codec Base Classes</span></a> for more
information on codec error handling.</p>
</dd></dl>
<dl class="function">
<dt id="codecs.decode">
<code class="descclassname">codecs.</code><code class="descname">decode</code><span class="sig-paren">(</span><em>obj</em>, <em>encoding='utf-8'</em>, <em>errors='strict'</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.decode" title="本定義的永久連結">¶</a></dt>
<dd><p>Decodes <em>obj</em> using the codec registered for <em>encoding</em>.</p>
<p><em>Errors</em> may be given to set the desired error handling scheme. The
default error handler is <code class="docutils literal notranslate"><span class="pre">'strict'</span></code> meaning that decoding errors raise
<a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> (or a more codec specific subclass, such as
<a class="reference internal" href="exceptions.html#UnicodeDecodeError" title="UnicodeDecodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code></a>). Refer to <a class="reference internal" href="#codec-base-classes"><span class="std std-ref">Codec Base Classes</span></a> for more
information on codec error handling.</p>
</dd></dl>
<p>The full details for each codec can also be looked up directly:</p>
<dl class="function">
<dt id="codecs.lookup">
<code class="descclassname">codecs.</code><code class="descname">lookup</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.lookup" title="本定義的永久連結">¶</a></dt>
<dd><p>Looks up the codec info in the Python codec registry and returns a
<a class="reference internal" href="#codecs.CodecInfo" title="codecs.CodecInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">CodecInfo</span></code></a> object as defined below.</p>
<p>Encodings are first looked up in the registry’s cache. If not found, the list of
registered search functions is scanned. If no <a class="reference internal" href="#codecs.CodecInfo" title="codecs.CodecInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">CodecInfo</span></code></a> object is
found, a <a class="reference internal" href="exceptions.html#LookupError" title="LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> is raised. Otherwise, the <a class="reference internal" href="#codecs.CodecInfo" title="codecs.CodecInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">CodecInfo</span></code></a> object
is stored in the cache and returned to the caller.</p>
</dd></dl>
<dl class="class">
<dt id="codecs.CodecInfo">
<em class="property">class </em><code class="descclassname">codecs.</code><code class="descname">CodecInfo</code><span class="sig-paren">(</span><em>encode</em>, <em>decode</em>, <em>streamreader=None</em>, <em>streamwriter=None</em>, <em>incrementalencoder=None</em>, <em>incrementaldecoder=None</em>, <em>name=None</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.CodecInfo" title="本定義的永久連結">¶</a></dt>
<dd><p>Codec details when looking up the codec registry. The constructor
arguments are stored in attributes of the same name:</p>
<dl class="attribute">
<dt id="codecs.CodecInfo.name">
<code class="descname">name</code><a class="headerlink" href="#codecs.CodecInfo.name" title="本定義的永久連結">¶</a></dt>
<dd><p>The name of the encoding.</p>
</dd></dl>
<dl class="attribute">
<dt id="codecs.CodecInfo.encode">
<code class="descname">encode</code><a class="headerlink" href="#codecs.CodecInfo.encode" title="本定義的永久連結">¶</a></dt>
<dt id="codecs.CodecInfo.decode">
<code class="descname">decode</code><a class="headerlink" href="#codecs.CodecInfo.decode" title="本定義的永久連結">¶</a></dt>
<dd><p>The stateless encoding and decoding functions. These must be
functions or methods which have the same interface as
the <a class="reference internal" href="#codecs.Codec.encode" title="codecs.Codec.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code></a> and <a class="reference internal" href="#codecs.Codec.decode" title="codecs.Codec.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code></a> methods of Codec
instances (see <a class="reference internal" href="#codec-objects"><span class="std std-ref">Codec Interface</span></a>).
The functions or methods are expected to work in a stateless mode.</p>
</dd></dl>
<dl class="attribute">
<dt id="codecs.CodecInfo.incrementalencoder">
<code class="descname">incrementalencoder</code><a class="headerlink" href="#codecs.CodecInfo.incrementalencoder" title="本定義的永久連結">¶</a></dt>
<dt id="codecs.CodecInfo.incrementaldecoder">
<code class="descname">incrementaldecoder</code><a class="headerlink" href="#codecs.CodecInfo.incrementaldecoder" title="本定義的永久連結">¶</a></dt>
<dd><p>Incremental encoder and decoder classes or factory functions.
These have to provide the interface defined by the base classes
<a class="reference internal" href="#codecs.IncrementalEncoder" title="codecs.IncrementalEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalEncoder</span></code></a> and <a class="reference internal" href="#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalDecoder</span></code></a>,
respectively. Incremental codecs can maintain state.</p>
</dd></dl>
<dl class="attribute">
<dt id="codecs.CodecInfo.streamwriter">
<code class="descname">streamwriter</code><a class="headerlink" href="#codecs.CodecInfo.streamwriter" title="本定義的永久連結">¶</a></dt>
<dt id="codecs.CodecInfo.streamreader">
<code class="descname">streamreader</code><a class="headerlink" href="#codecs.CodecInfo.streamreader" title="本定義的永久連結">¶</a></dt>
<dd><p>Stream writer and reader classes or factory functions. These have to
provide the interface defined by the base classes
<a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> and <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a>, respectively.
Stream codecs can maintain state.</p>
</dd></dl>
</dd></dl>
<p>To simplify access to the various codec components, the module provides
these additional functions which use <a class="reference internal" href="#codecs.lookup" title="codecs.lookup"><code class="xref py py-func docutils literal notranslate"><span class="pre">lookup()</span></code></a> for the codec lookup:</p>
<dl class="function">
<dt id="codecs.getencoder">
<code class="descclassname">codecs.</code><code class="descname">getencoder</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.getencoder" title="本定義的永久連結">¶</a></dt>
<dd><p>Look up the codec for the given encoding and return its encoder function.</p>
<p>Raises a <a class="reference internal" href="exceptions.html#LookupError" title="LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> in case the encoding cannot be found.</p>
</dd></dl>
<dl class="function">
<dt id="codecs.getdecoder">
<code class="descclassname">codecs.</code><code class="descname">getdecoder</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.getdecoder" title="本定義的永久連結">¶</a></dt>
<dd><p>Look up the codec for the given encoding and return its decoder function.</p>
<p>Raises a <a class="reference internal" href="exceptions.html#LookupError" title="LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> in case the encoding cannot be found.</p>
</dd></dl>
<dl class="function">
<dt id="codecs.getincrementalencoder">
<code class="descclassname">codecs.</code><code class="descname">getincrementalencoder</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.getincrementalencoder" title="本定義的永久連結">¶</a></dt>
<dd><p>Look up the codec for the given encoding and return its incremental encoder
class or factory function.</p>
<p>Raises a <a class="reference internal" href="exceptions.html#LookupError" title="LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> in case the encoding cannot be found or the codec
doesn’t support an incremental encoder.</p>
</dd></dl>
<dl class="function">
<dt id="codecs.getincrementaldecoder">
<code class="descclassname">codecs.</code><code class="descname">getincrementaldecoder</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.getincrementaldecoder" title="本定義的永久連結">¶</a></dt>
<dd><p>Look up the codec for the given encoding and return its incremental decoder
class or factory function.</p>
<p>Raises a <a class="reference internal" href="exceptions.html#LookupError" title="LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> in case the encoding cannot be found or the codec
doesn’t support an incremental decoder.</p>
</dd></dl>
<dl class="function">
<dt id="codecs.getreader">
<code class="descclassname">codecs.</code><code class="descname">getreader</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.getreader" title="本定義的永久連結">¶</a></dt>
<dd><p>Look up the codec for the given encoding and return its <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a>
class or factory function.</p>
<p>Raises a <a class="reference internal" href="exceptions.html#LookupError" title="LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> in case the encoding cannot be found.</p>
</dd></dl>
<dl class="function">
<dt id="codecs.getwriter">
<code class="descclassname">codecs.</code><code class="descname">getwriter</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.getwriter" title="本定義的永久連結">¶</a></dt>
<dd><p>Look up the codec for the given encoding and return its <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a>
class or factory function.</p>
<p>Raises a <a class="reference internal" href="exceptions.html#LookupError" title="LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> in case the encoding cannot be found.</p>
</dd></dl>
<p>Custom codecs are made available by registering a suitable codec search
function:</p>
<dl class="function">
<dt id="codecs.register">
<code class="descclassname">codecs.</code><code class="descname">register</code><span class="sig-paren">(</span><em>search_function</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.register" title="本定義的永久連結">¶</a></dt>
<dd><p>Register a codec search function. Search functions are expected to take one
argument, being the encoding name in all lower case letters, and return a
<a class="reference internal" href="#codecs.CodecInfo" title="codecs.CodecInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">CodecInfo</span></code></a> object. In case a search function cannot find
a given encoding, it should return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">備註</p>
<p class="last">Search function registration is not currently reversible,
which may cause problems in some cases, such as unit testing or
module reloading.</p>
</div>
</dd></dl>
<p>While the builtin <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> and the associated <a class="reference internal" href="io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module are the
recommended approach for working with encoded text files, this module
provides additional utility functions and classes that allow the use of a
wider range of codecs when working with binary files:</p>
<dl class="function">
<dt id="codecs.open">
<code class="descclassname">codecs.</code><code class="descname">open</code><span class="sig-paren">(</span><em>filename</em>, <em>mode='r'</em>, <em>encoding=None</em>, <em>errors='strict'</em>, <em>buffering=1</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.open" title="本定義的永久連結">¶</a></dt>
<dd><p>Open an encoded file using the given <em>mode</em> and return an instance of
<a class="reference internal" href="#codecs.StreamReaderWriter" title="codecs.StreamReaderWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReaderWriter</span></code></a>, providing transparent encoding/decoding.
The default file mode is <code class="docutils literal notranslate"><span class="pre">'r'</span></code>, meaning to open the file in read mode.</p>
<div class="admonition note">
<p class="first admonition-title">備註</p>
<p class="last">Underlying encoded files are always opened in binary mode.
No automatic conversion of <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> is done on reading and writing.
The <em>mode</em> argument may be any binary mode acceptable to the built-in
<a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function; the <code class="docutils literal notranslate"><span class="pre">'b'</span></code> is automatically added.</p>
</div>
<p><em>encoding</em> specifies the encoding which is to be used for the file.
Any encoding that encodes to and decodes from bytes is allowed, and
the data types supported by the file methods depend on the codec used.</p>
<p><em>errors</em> may be given to define the error handling. It defaults to <code class="docutils literal notranslate"><span class="pre">'strict'</span></code>
which causes a <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> to be raised in case an encoding error occurs.</p>
<p><em>buffering</em> has the same meaning as for the built-in <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function. It
defaults to line buffered.</p>
</dd></dl>
<dl class="function">
<dt id="codecs.EncodedFile">
<code class="descclassname">codecs.</code><code class="descname">EncodedFile</code><span class="sig-paren">(</span><em>file</em>, <em>data_encoding</em>, <em>file_encoding=None</em>, <em>errors='strict'</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.EncodedFile" title="本定義的永久連結">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="#codecs.StreamRecoder" title="codecs.StreamRecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamRecoder</span></code></a> instance, a wrapped version of <em>file</em>
which provides transparent transcoding. The original file is closed
when the wrapped version is closed.</p>
<p>Data written to the wrapped file is decoded according to the given
<em>data_encoding</em> and then written to the original file as bytes using
<em>file_encoding</em>. Bytes read from the original file are decoded
according to <em>file_encoding</em>, and the result is encoded
using <em>data_encoding</em>.</p>
<p>If <em>file_encoding</em> is not given, it defaults to <em>data_encoding</em>.</p>
<p><em>errors</em> may be given to define the error handling. It defaults to
<code class="docutils literal notranslate"><span class="pre">'strict'</span></code>, which causes <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> to be raised in case an encoding
error occurs.</p>
</dd></dl>
<dl class="function">
<dt id="codecs.iterencode">
<code class="descclassname">codecs.</code><code class="descname">iterencode</code><span class="sig-paren">(</span><em>iterator</em>, <em>encoding</em>, <em>errors='strict'</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.iterencode" title="本定義的永久連結">¶</a></dt>
<dd><p>Uses an incremental encoder to iteratively encode the input provided by
<em>iterator</em>. This function is a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>.
The <em>errors</em> argument (as well as any
other keyword argument) is passed through to the incremental encoder.</p>
<p>This function requires that the codec accept text <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> objects
to encode. Therefore it does not support bytes-to-bytes encoders such as
<code class="docutils literal notranslate"><span class="pre">base64_codec</span></code>.</p>
</dd></dl>
<dl class="function">
<dt id="codecs.iterdecode">
<code class="descclassname">codecs.</code><code class="descname">iterdecode</code><span class="sig-paren">(</span><em>iterator</em>, <em>encoding</em>, <em>errors='strict'</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.iterdecode" title="本定義的永久連結">¶</a></dt>
<dd><p>Uses an incremental decoder to iteratively decode the input provided by
<em>iterator</em>. This function is a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>.
The <em>errors</em> argument (as well as any
other keyword argument) is passed through to the incremental decoder.</p>
<p>This function requires that the codec accept <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> objects
to decode. Therefore it does not support text-to-text encoders such as
<code class="docutils literal notranslate"><span class="pre">rot_13</span></code>, although <code class="docutils literal notranslate"><span class="pre">rot_13</span></code> may be used equivalently with
<a class="reference internal" href="#codecs.iterencode" title="codecs.iterencode"><code class="xref py py-func docutils literal notranslate"><span class="pre">iterencode()</span></code></a>.</p>
</dd></dl>
<p>The module also provides the following constants which are useful for reading
and writing to platform dependent files:</p>
<dl class="data">
<dt id="codecs.BOM">
<code class="descclassname">codecs.</code><code class="descname">BOM</code><a class="headerlink" href="#codecs.BOM" title="本定義的永久連結">¶</a></dt>
<dt id="codecs.BOM_BE">
<code class="descclassname">codecs.</code><code class="descname">BOM_BE</code><a class="headerlink" href="#codecs.BOM_BE" title="本定義的永久連結">¶</a></dt>
<dt id="codecs.BOM_LE">
<code class="descclassname">codecs.</code><code class="descname">BOM_LE</code><a class="headerlink" href="#codecs.BOM_LE" title="本定義的永久連結">¶</a></dt>
<dt id="codecs.BOM_UTF8">
<code class="descclassname">codecs.</code><code class="descname">BOM_UTF8</code><a class="headerlink" href="#codecs.BOM_UTF8" title="本定義的永久連結">¶</a></dt>
<dt id="codecs.BOM_UTF16">
<code class="descclassname">codecs.</code><code class="descname">BOM_UTF16</code><a class="headerlink" href="#codecs.BOM_UTF16" title="本定義的永久連結">¶</a></dt>
<dt id="codecs.BOM_UTF16_BE">
<code class="descclassname">codecs.</code><code class="descname">BOM_UTF16_BE</code><a class="headerlink" href="#codecs.BOM_UTF16_BE" title="本定義的永久連結">¶</a></dt>
<dt id="codecs.BOM_UTF16_LE">
<code class="descclassname">codecs.</code><code class="descname">BOM_UTF16_LE</code><a class="headerlink" href="#codecs.BOM_UTF16_LE" title="本定義的永久連結">¶</a></dt>
<dt id="codecs.BOM_UTF32">
<code class="descclassname">codecs.</code><code class="descname">BOM_UTF32</code><a class="headerlink" href="#codecs.BOM_UTF32" title="本定義的永久連結">¶</a></dt>
<dt id="codecs.BOM_UTF32_BE">
<code class="descclassname">codecs.</code><code class="descname">BOM_UTF32_BE</code><a class="headerlink" href="#codecs.BOM_UTF32_BE" title="本定義的永久連結">¶</a></dt>
<dt id="codecs.BOM_UTF32_LE">
<code class="descclassname">codecs.</code><code class="descname">BOM_UTF32_LE</code><a class="headerlink" href="#codecs.BOM_UTF32_LE" title="本定義的永久連結">¶</a></dt>
<dd><p>These constants define various byte sequences,
being Unicode byte order marks (BOMs) for several encodings. They are
used in UTF-16 and UTF-32 data streams to indicate the byte order used,
and in UTF-8 as a Unicode signature. <a class="reference internal" href="#codecs.BOM_UTF16" title="codecs.BOM_UTF16"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_UTF16</span></code></a> is either
<a class="reference internal" href="#codecs.BOM_UTF16_BE" title="codecs.BOM_UTF16_BE"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_UTF16_BE</span></code></a> or <a class="reference internal" href="#codecs.BOM_UTF16_LE" title="codecs.BOM_UTF16_LE"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_UTF16_LE</span></code></a> depending on the platform’s
native byte order, <a class="reference internal" href="#codecs.BOM" title="codecs.BOM"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM</span></code></a> is an alias for <a class="reference internal" href="#codecs.BOM_UTF16" title="codecs.BOM_UTF16"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_UTF16</span></code></a>,
<a class="reference internal" href="#codecs.BOM_LE" title="codecs.BOM_LE"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_LE</span></code></a> for <a class="reference internal" href="#codecs.BOM_UTF16_LE" title="codecs.BOM_UTF16_LE"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_UTF16_LE</span></code></a> and <a class="reference internal" href="#codecs.BOM_BE" title="codecs.BOM_BE"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_BE</span></code></a> for
<a class="reference internal" href="#codecs.BOM_UTF16_BE" title="codecs.BOM_UTF16_BE"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_UTF16_BE</span></code></a>. The others represent the BOM in UTF-8 and UTF-32
encodings.</p>
</dd></dl>
<div class="section" id="codec-base-classes">
<span id="id1"></span><h2>7.2.1. Codec Base Classes<a class="headerlink" href="#codec-base-classes" title="本標題的永久連結">¶</a></h2>
<p>The <a class="reference internal" href="#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module defines a set of base classes which define the
interfaces for working with codec objects, and can also be used as the basis
for custom codec implementations.</p>
<p>Each codec has to define four interfaces to make it usable as codec in Python:
stateless encoder, stateless decoder, stream reader and stream writer. The
stream reader and writers typically reuse the stateless encoder/decoder to
implement the file protocols. Codec authors also need to define how the
codec will handle encoding and decoding errors.</p>
<div class="section" id="error-handlers">
<span id="surrogateescape"></span><span id="id2"></span><h3>7.2.1.1. Error Handlers<a class="headerlink" href="#error-handlers" title="本標題的永久連結">¶</a></h3>
<p>To simplify and standardize error handling,
codecs may implement different error handling schemes by
accepting the <em>errors</em> string argument. The following string values are
defined and implemented by all standard Python codecs:</p>
<table border="1" class="docutils">
<colgroup>
<col width="35%" />
<col width="65%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'strict'</span></code></td>
<td>Raise <a class="reference internal" href="exceptions.html#UnicodeError" title="UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a> (or a subclass);
this is the default. Implemented in
<a class="reference internal" href="#codecs.strict_errors" title="codecs.strict_errors"><code class="xref py py-func docutils literal notranslate"><span class="pre">strict_errors()</span></code></a>.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'ignore'</span></code></td>
<td>Ignore the malformed data and continue
without further notice. Implemented in
<a class="reference internal" href="#codecs.ignore_errors" title="codecs.ignore_errors"><code class="xref py py-func docutils literal notranslate"><span class="pre">ignore_errors()</span></code></a>.</td>
</tr>
</tbody>
</table>
<p>The following error handlers are only applicable to
<a class="reference internal" href="../glossary.html#term-text-encoding"><span class="xref std std-term">text encodings</span></a>:</p>
<table border="1" class="docutils">
<colgroup>
<col width="35%" />
<col width="65%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'replace'</span></code></td>
<td>Replace with a suitable replacement
marker; Python will use the official
<code class="docutils literal notranslate"><span class="pre">U+FFFD</span></code> REPLACEMENT CHARACTER for the
built-in codecs on decoding, and 『?』 on
encoding. Implemented in
<a class="reference internal" href="#codecs.replace_errors" title="codecs.replace_errors"><code class="xref py py-func docutils literal notranslate"><span class="pre">replace_errors()</span></code></a>.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'xmlcharrefreplace'</span></code></td>
<td>Replace with the appropriate XML character
reference (only for encoding). Implemented
in <a class="reference internal" href="#codecs.xmlcharrefreplace_errors" title="codecs.xmlcharrefreplace_errors"><code class="xref py py-func docutils literal notranslate"><span class="pre">xmlcharrefreplace_errors()</span></code></a>.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'backslashreplace'</span></code></td>
<td>Replace with backslashed escape sequences.
Implemented in
<a class="reference internal" href="#codecs.backslashreplace_errors" title="codecs.backslashreplace_errors"><code class="xref py py-func docutils literal notranslate"><span class="pre">backslashreplace_errors()</span></code></a>.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'namereplace'</span></code></td>
<td>Replace with <code class="docutils literal notranslate"><span class="pre">\N{...}</span></code> escape sequences
(only for encoding). Implemented in
<a class="reference internal" href="#codecs.namereplace_errors" title="codecs.namereplace_errors"><code class="xref py py-func docutils literal notranslate"><span class="pre">namereplace_errors()</span></code></a>.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'surrogateescape'</span></code></td>
<td>On decoding, replace byte with individual
surrogate code ranging from <code class="docutils literal notranslate"><span class="pre">U+DC80</span></code> to
<code class="docutils literal notranslate"><span class="pre">U+DCFF</span></code>. This code will then be turned
back into the same byte when the
<code class="docutils literal notranslate"><span class="pre">'surrogateescape'</span></code> error handler is used
when encoding the data. (See <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0383"><strong>PEP 383</strong></a> for
more.)</td>
</tr>
</tbody>
</table>
<p>In addition, the following error handler is specific to the given codecs:</p>
<table border="1" class="docutils">
<colgroup>
<col width="22%" />
<col width="28%" />
<col width="50%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value</th>
<th class="head">Codecs</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'surrogatepass'</span></code></td>
<td>utf-8, utf-16, utf-32,
utf-16-be, utf-16-le,
utf-32-be, utf-32-le</td>
<td>Allow encoding and decoding of surrogate
codes. These codecs normally treat the
presence of surrogates as an error.</td>
</tr>
</tbody>
</table>
<div class="versionadded">
<p><span class="versionmodified">3.1 版新加入: </span>The <code class="docutils literal notranslate"><span class="pre">'surrogateescape'</span></code> and <code class="docutils literal notranslate"><span class="pre">'surrogatepass'</span></code> error handlers.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">3.4 版更變: </span>The <code class="docutils literal notranslate"><span class="pre">'surrogatepass'</span></code> error handlers now works with utf-16* and utf-32* codecs.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">3.5 版新加入: </span>The <code class="docutils literal notranslate"><span class="pre">'namereplace'</span></code> error handler.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">3.5 版更變: </span>The <code class="docutils literal notranslate"><span class="pre">'backslashreplace'</span></code> error handlers now works with decoding and
translating.</p>
</div>
<p>The set of allowed values can be extended by registering a new named error
handler:</p>
<dl class="function">
<dt id="codecs.register_error">
<code class="descclassname">codecs.</code><code class="descname">register_error</code><span class="sig-paren">(</span><em>name</em>, <em>error_handler</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.register_error" title="本定義的永久連結">¶</a></dt>
<dd><p>Register the error handling function <em>error_handler</em> under the name <em>name</em>.
The <em>error_handler</em> argument will be called during encoding and decoding
in case of an error, when <em>name</em> is specified as the errors parameter.</p>
<p>For encoding, <em>error_handler</em> will be called with a <a class="reference internal" href="exceptions.html#UnicodeEncodeError" title="UnicodeEncodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code></a>
instance, which contains information about the location of the error. The
error handler must either raise this or a different exception, or return a
tuple with a replacement for the unencodable part of the input and a position
where encoding should continue. The replacement may be either <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> or
<a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>. If the replacement is bytes, the encoder will simply copy
them into the output buffer. If the replacement is a string, the encoder will
encode the replacement. Encoding continues on original input at the
specified position. Negative position values will be treated as being
relative to the end of the input string. If the resulting position is out of
bound an <a class="reference internal" href="exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> will be raised.</p>
<p>Decoding and translating works similarly, except <a class="reference internal" href="exceptions.html#UnicodeDecodeError" title="UnicodeDecodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code></a> or
<a class="reference internal" href="exceptions.html#UnicodeTranslateError" title="UnicodeTranslateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeTranslateError</span></code></a> will be passed to the handler and that the
replacement from the error handler will be put into the output directly.</p>
</dd></dl>
<p>Previously registered error handlers (including the standard error handlers)
can be looked up by name:</p>
<dl class="function">
<dt id="codecs.lookup_error">
<code class="descclassname">codecs.</code><code class="descname">lookup_error</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.lookup_error" title="本定義的永久連結">¶</a></dt>
<dd><p>Return the error handler previously registered under the name <em>name</em>.</p>
<p>Raises a <a class="reference internal" href="exceptions.html#LookupError" title="LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> in case the handler cannot be found.</p>
</dd></dl>
<p>The following standard error handlers are also made available as module level
functions:</p>
<dl class="function">
<dt id="codecs.strict_errors">
<code class="descclassname">codecs.</code><code class="descname">strict_errors</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.strict_errors" title="本定義的永久連結">¶</a></dt>
<dd><p>Implements the <code class="docutils literal notranslate"><span class="pre">'strict'</span></code> error handling: each encoding or
decoding error raises a <a class="reference internal" href="exceptions.html#UnicodeError" title="UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a>.</p>
</dd></dl>
<dl class="function">
<dt id="codecs.replace_errors">
<code class="descclassname">codecs.</code><code class="descname">replace_errors</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.replace_errors" title="本定義的永久連結">¶</a></dt>
<dd><p>Implements the <code class="docutils literal notranslate"><span class="pre">'replace'</span></code> error handling (for <a class="reference internal" href="../glossary.html#term-text-encoding"><span class="xref std std-term">text encodings</span></a> only): substitutes <code class="docutils literal notranslate"><span class="pre">'?'</span></code> for encoding errors
(to be encoded by the codec), and <code class="docutils literal notranslate"><span class="pre">'\ufffd'</span></code> (the Unicode replacement
character) for decoding errors.</p>
</dd></dl>
<dl class="function">
<dt id="codecs.ignore_errors">
<code class="descclassname">codecs.</code><code class="descname">ignore_errors</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.ignore_errors" title="本定義的永久連結">¶</a></dt>
<dd><p>Implements the <code class="docutils literal notranslate"><span class="pre">'ignore'</span></code> error handling: malformed data is ignored and
encoding or decoding is continued without further notice.</p>
</dd></dl>
<dl class="function">
<dt id="codecs.xmlcharrefreplace_errors">
<code class="descclassname">codecs.</code><code class="descname">xmlcharrefreplace_errors</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.xmlcharrefreplace_errors" title="本定義的永久連結">¶</a></dt>
<dd><p>Implements the <code class="docutils literal notranslate"><span class="pre">'xmlcharrefreplace'</span></code> error handling (for encoding with
<a class="reference internal" href="../glossary.html#term-text-encoding"><span class="xref std std-term">text encodings</span></a> only): the
unencodable character is replaced by an appropriate XML character reference.</p>
</dd></dl>
<dl class="function">
<dt id="codecs.backslashreplace_errors">
<code class="descclassname">codecs.</code><code class="descname">backslashreplace_errors</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.backslashreplace_errors" title="本定義的永久連結">¶</a></dt>
<dd><p>Implements the <code class="docutils literal notranslate"><span class="pre">'backslashreplace'</span></code> error handling (for
<a class="reference internal" href="../glossary.html#term-text-encoding"><span class="xref std std-term">text encodings</span></a> only): malformed data is
replaced by a backslashed escape sequence.</p>
</dd></dl>
<dl class="function">
<dt id="codecs.namereplace_errors">
<code class="descclassname">codecs.</code><code class="descname">namereplace_errors</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.namereplace_errors" title="本定義的永久連結">¶</a></dt>
<dd><p>Implements the <code class="docutils literal notranslate"><span class="pre">'namereplace'</span></code> error handling (for encoding with
<a class="reference internal" href="../glossary.html#term-text-encoding"><span class="xref std std-term">text encodings</span></a> only): the
unencodable character is replaced by a <code class="docutils literal notranslate"><span class="pre">\N{...}</span></code> escape sequence.</p>
<div class="versionadded">
<p><span class="versionmodified">3.5 版新加入.</span></p>
</div>
</dd></dl>
</div>
<div class="section" id="stateless-encoding-and-decoding">
<span id="codec-objects"></span><h3>7.2.1.2. Stateless Encoding and Decoding<a class="headerlink" href="#stateless-encoding-and-decoding" title="本標題的永久連結">¶</a></h3>
<p>The base <code class="xref py py-class docutils literal notranslate"><span class="pre">Codec</span></code> class defines these methods which also define the
function interfaces of the stateless encoder and decoder:</p>
<dl class="method">
<dt id="codecs.Codec.encode">
<code class="descclassname">Codec.</code><code class="descname">encode</code><span class="sig-paren">(</span><em>input</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.Codec.encode" title="本定義的永久連結">¶</a></dt>
<dd><p>Encodes the object <em>input</em> and returns a tuple (output object, length consumed).
For instance, <a class="reference internal" href="../glossary.html#term-text-encoding"><span class="xref std std-term">text encoding</span></a> converts
a string object to a bytes object using a particular
character set encoding (e.g., <code class="docutils literal notranslate"><span class="pre">cp1252</span></code> or <code class="docutils literal notranslate"><span class="pre">iso-8859-1</span></code>).</p>
<p>The <em>errors</em> argument defines the error handling to apply.
It defaults to <code class="docutils literal notranslate"><span class="pre">'strict'</span></code> handling.</p>
<p>The method may not store state in the <code class="xref py py-class docutils literal notranslate"><span class="pre">Codec</span></code> instance. Use
<a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> for codecs which have to keep state in order to make
encoding efficient.</p>
<p>The encoder must be able to handle zero length input and return an empty object
of the output object type in this situation.</p>
</dd></dl>
<dl class="method">
<dt id="codecs.Codec.decode">
<code class="descclassname">Codec.</code><code class="descname">decode</code><span class="sig-paren">(</span><em>input</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.Codec.decode" title="本定義的永久連結">¶</a></dt>
<dd><p>Decodes the object <em>input</em> and returns a tuple (output object, length
consumed). For instance, for a <a class="reference internal" href="../glossary.html#term-text-encoding"><span class="xref std std-term">text encoding</span></a>, decoding converts
a bytes object encoded using a particular
character set encoding to a string object.</p>
<p>For text encodings and bytes-to-bytes codecs,
<em>input</em> must be a bytes object or one which provides the read-only
buffer interface – for example, buffer objects and memory mapped files.</p>
<p>The <em>errors</em> argument defines the error handling to apply.
It defaults to <code class="docutils literal notranslate"><span class="pre">'strict'</span></code> handling.</p>
<p>The method may not store state in the <code class="xref py py-class docutils literal notranslate"><span class="pre">Codec</span></code> instance. Use
<a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> for codecs which have to keep state in order to make
decoding efficient.</p>
<p>The decoder must be able to handle zero length input and return an empty object
of the output object type in this situation.</p>
</dd></dl>
</div>
<div class="section" id="incremental-encoding-and-decoding">
<h3>7.2.1.3. Incremental Encoding and Decoding<a class="headerlink" href="#incremental-encoding-and-decoding" title="本標題的永久連結">¶</a></h3>
<p>The <a class="reference internal" href="#codecs.IncrementalEncoder" title="codecs.IncrementalEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalEncoder</span></code></a> and <a class="reference internal" href="#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalDecoder</span></code></a> classes provide
the basic interface for incremental encoding and decoding. Encoding/decoding the
input isn’t done with one call to the stateless encoder/decoder function, but
with multiple calls to the
<a class="reference internal" href="#codecs.IncrementalEncoder.encode" title="codecs.IncrementalEncoder.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code></a>/<a class="reference internal" href="#codecs.IncrementalDecoder.decode" title="codecs.IncrementalDecoder.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code></a> method of
the incremental encoder/decoder. The incremental encoder/decoder keeps track of
the encoding/decoding process during method calls.</p>
<p>The joined output of calls to the
<a class="reference internal" href="#codecs.IncrementalEncoder.encode" title="codecs.IncrementalEncoder.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code></a>/<a class="reference internal" href="#codecs.IncrementalDecoder.decode" title="codecs.IncrementalDecoder.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code></a> method is
the same as if all the single inputs were joined into one, and this input was
encoded/decoded with the stateless encoder/decoder.</p>
<div class="section" id="incrementalencoder-objects">
<span id="incremental-encoder-objects"></span><h4>7.2.1.3.1. IncrementalEncoder Objects<a class="headerlink" href="#incrementalencoder-objects" title="本標題的永久連結">¶</a></h4>
<p>The <a class="reference internal" href="#codecs.IncrementalEncoder" title="codecs.IncrementalEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalEncoder</span></code></a> class is used for encoding an input in multiple
steps. It defines the following methods which every incremental encoder must
define in order to be compatible with the Python codec registry.</p>
<dl class="class">
<dt id="codecs.IncrementalEncoder">
<em class="property">class </em><code class="descclassname">codecs.</code><code class="descname">IncrementalEncoder</code><span class="sig-paren">(</span><em>errors='strict'</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalEncoder" title="本定義的永久連結">¶</a></dt>
<dd><p>Constructor for an <a class="reference internal" href="#codecs.IncrementalEncoder" title="codecs.IncrementalEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalEncoder</span></code></a> instance.</p>
<p>All incremental encoders must provide this constructor interface. They are free
to add additional keyword arguments, but only the ones defined here are used by
the Python codec registry.</p>
<p>The <a class="reference internal" href="#codecs.IncrementalEncoder" title="codecs.IncrementalEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalEncoder</span></code></a> may implement different error handling schemes
by providing the <em>errors</em> keyword argument. See <a class="reference internal" href="#error-handlers"><span class="std std-ref">Error Handlers</span></a> for
possible values.</p>
<p>The <em>errors</em> argument will be assigned to an attribute of the same name.
Assigning to this attribute makes it possible to switch between different error
handling strategies during the lifetime of the <a class="reference internal" href="#codecs.IncrementalEncoder" title="codecs.IncrementalEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalEncoder</span></code></a>
object.</p>
<dl class="method">
<dt id="codecs.IncrementalEncoder.encode">
<code class="descname">encode</code><span class="sig-paren">(</span><em>object</em><span class="optional">[</span>, <em>final</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalEncoder.encode" title="本定義的永久連結">¶</a></dt>
<dd><p>Encodes <em>object</em> (taking the current state of the encoder into account)
and returns the resulting encoded object. If this is the last call to
<a class="reference internal" href="#codecs.encode" title="codecs.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code></a> <em>final</em> must be true (the default is false).</p>
</dd></dl>
<dl class="method">
<dt id="codecs.IncrementalEncoder.reset">
<code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalEncoder.reset" title="本定義的永久連結">¶</a></dt>
<dd><p>Reset the encoder to the initial state. The output is discarded: call
<code class="docutils literal notranslate"><span class="pre">.encode(object,</span> <span class="pre">final=True)</span></code>, passing an empty byte or text string
if necessary, to reset the encoder and to get the output.</p>
</dd></dl>
<dl class="method">
<dt id="codecs.IncrementalEncoder.getstate">
<code class="descname">getstate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalEncoder.getstate" title="本定義的永久連結">¶</a></dt>
<dd><p>Return the current state of the encoder which must be an integer. The
implementation should make sure that <code class="docutils literal notranslate"><span class="pre">0</span></code> is the most common
state. (States that are more complicated than integers can be converted
into an integer by marshaling/pickling the state and encoding the bytes
of the resulting string into an integer).</p>
</dd></dl>
<dl class="method">
<dt id="codecs.IncrementalEncoder.setstate">
<code class="descname">setstate</code><span class="sig-paren">(</span><em>state</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalEncoder.setstate" title="本定義的永久連結">¶</a></dt>
<dd><p>Set the state of the encoder to <em>state</em>. <em>state</em> must be an encoder state
returned by <a class="reference internal" href="#codecs.IncrementalEncoder.getstate" title="codecs.IncrementalEncoder.getstate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getstate()</span></code></a>.</p>
</dd></dl>
</dd></dl>
</div>
<div class="section" id="incrementaldecoder-objects">
<span id="incremental-decoder-objects"></span><h4>7.2.1.3.2. IncrementalDecoder Objects<a class="headerlink" href="#incrementaldecoder-objects" title="本標題的永久連結">¶</a></h4>
<p>The <a class="reference internal" href="#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalDecoder</span></code></a> class is used for decoding an input in multiple
steps. It defines the following methods which every incremental decoder must
define in order to be compatible with the Python codec registry.</p>
<dl class="class">
<dt id="codecs.IncrementalDecoder">
<em class="property">class </em><code class="descclassname">codecs.</code><code class="descname">IncrementalDecoder</code><span class="sig-paren">(</span><em>errors='strict'</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalDecoder" title="本定義的永久連結">¶</a></dt>
<dd><p>Constructor for an <a class="reference internal" href="#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalDecoder</span></code></a> instance.</p>
<p>All incremental decoders must provide this constructor interface. They are free
to add additional keyword arguments, but only the ones defined here are used by
the Python codec registry.</p>
<p>The <a class="reference internal" href="#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalDecoder</span></code></a> may implement different error handling schemes
by providing the <em>errors</em> keyword argument. See <a class="reference internal" href="#error-handlers"><span class="std std-ref">Error Handlers</span></a> for
possible values.</p>
<p>The <em>errors</em> argument will be assigned to an attribute of the same name.
Assigning to this attribute makes it possible to switch between different error
handling strategies during the lifetime of the <a class="reference internal" href="#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalDecoder</span></code></a>
object.</p>
<dl class="method">
<dt id="codecs.IncrementalDecoder.decode">
<code class="descname">decode</code><span class="sig-paren">(</span><em>object</em><span class="optional">[</span>, <em>final</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalDecoder.decode" title="本定義的永久連結">¶</a></dt>
<dd><p>Decodes <em>object</em> (taking the current state of the decoder into account)
and returns the resulting decoded object. If this is the last call to
<a class="reference internal" href="#codecs.decode" title="codecs.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code></a> <em>final</em> must be true (the default is false). If <em>final</em> is
true the decoder must decode the input completely and must flush all
buffers. If this isn’t possible (e.g. because of incomplete byte sequences
at the end of the input) it must initiate error handling just like in the
stateless case (which might raise an exception).</p>
</dd></dl>
<dl class="method">
<dt id="codecs.IncrementalDecoder.reset">
<code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalDecoder.reset" title="本定義的永久連結">¶</a></dt>
<dd><p>Reset the decoder to the initial state.</p>
</dd></dl>
<dl class="method">
<dt id="codecs.IncrementalDecoder.getstate">
<code class="descname">getstate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalDecoder.getstate" title="本定義的永久連結">¶</a></dt>
<dd><p>Return the current state of the decoder. This must be a tuple with two
items, the first must be the buffer containing the still undecoded
input. The second must be an integer and can be additional state
info. (The implementation should make sure that <code class="docutils literal notranslate"><span class="pre">0</span></code> is the most common
additional state info.) If this additional state info is <code class="docutils literal notranslate"><span class="pre">0</span></code> it must be
possible to set the decoder to the state which has no input buffered and
<code class="docutils literal notranslate"><span class="pre">0</span></code> as the additional state info, so that feeding the previously
buffered input to the decoder returns it to the previous state without
producing any output. (Additional state info that is more complicated than
integers can be converted into an integer by marshaling/pickling the info
and encoding the bytes of the resulting string into an integer.)</p>
</dd></dl>
<dl class="method">
<dt id="codecs.IncrementalDecoder.setstate">
<code class="descname">setstate</code><span class="sig-paren">(</span><em>state</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalDecoder.setstate" title="本定義的永久連結">¶</a></dt>
<dd><p>Set the state of the encoder to <em>state</em>. <em>state</em> must be a decoder state
returned by <a class="reference internal" href="#codecs.IncrementalDecoder.getstate" title="codecs.IncrementalDecoder.getstate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getstate()</span></code></a>.</p>
</dd></dl>
</dd></dl>
</div>
</div>
<div class="section" id="stream-encoding-and-decoding">
<h3>7.2.1.4. Stream Encoding and Decoding<a class="headerlink" href="#stream-encoding-and-decoding" title="本標題的永久連結">¶</a></h3>
<p>The <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> and <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> classes provide generic
working interfaces which can be used to implement new encoding submodules very
easily. See <code class="xref py py-mod docutils literal notranslate"><span class="pre">encodings.utf_8</span></code> for an example of how this is done.</p>
<div class="section" id="streamwriter-objects">
<span id="stream-writer-objects"></span><h4>7.2.1.4.1. StreamWriter Objects<a class="headerlink" href="#streamwriter-objects" title="本標題的永久連結">¶</a></h4>
<p>The <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> class is a subclass of <code class="xref py py-class docutils literal notranslate"><span class="pre">Codec</span></code> and defines the
following methods which every stream writer must define in order to be
compatible with the Python codec registry.</p>
<dl class="class">
<dt id="codecs.StreamWriter">
<em class="property">class </em><code class="descclassname">codecs.</code><code class="descname">StreamWriter</code><span class="sig-paren">(</span><em>stream</em>, <em>errors='strict'</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamWriter" title="本定義的永久連結">¶</a></dt>
<dd><p>Constructor for a <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> instance.</p>
<p>All stream writers must provide this constructor interface. They are free to add
additional keyword arguments, but only the ones defined here are used by the
Python codec registry.</p>
<p>The <em>stream</em> argument must be a file-like object open for writing
text or binary data, as appropriate for the specific codec.</p>
<p>The <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> may implement different error handling schemes by
providing the <em>errors</em> keyword argument. See <a class="reference internal" href="#error-handlers"><span class="std std-ref">Error Handlers</span></a> for
the standard error handlers the underlying stream codec may support.</p>
<p>The <em>errors</em> argument will be assigned to an attribute of the same name.
Assigning to this attribute makes it possible to switch between different error
handling strategies during the lifetime of the <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> object.</p>
<dl class="method">
<dt id="codecs.StreamWriter.write">
<code class="descname">write</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamWriter.write" title="本定義的永久連結">¶</a></dt>
<dd><p>Writes the object’s contents encoded to the stream.</p>
</dd></dl>
<dl class="method">
<dt id="codecs.StreamWriter.writelines">
<code class="descname">writelines</code><span class="sig-paren">(</span><em>list</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamWriter.writelines" title="本定義的永久連結">¶</a></dt>
<dd><p>Writes the concatenated list of strings to the stream (possibly by reusing
the <a class="reference internal" href="#codecs.StreamWriter.write" title="codecs.StreamWriter.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> method). The standard bytes-to-bytes codecs
do not support this method.</p>
</dd></dl>
<dl class="method">
<dt id="codecs.StreamWriter.reset">
<code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamWriter.reset" title="本定義的永久連結">¶</a></dt>
<dd><p>Flushes and resets the codec buffers used for keeping state.</p>
<p>Calling this method should ensure that the data on the output is put into
a clean state that allows appending of new fresh data without having to
rescan the whole stream to recover state.</p>
</dd></dl>
</dd></dl>
<p>In addition to the above methods, the <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> must also inherit
all other methods and attributes from the underlying stream.</p>
</div>
<div class="section" id="streamreader-objects">
<span id="stream-reader-objects"></span><h4>7.2.1.4.2. StreamReader Objects<a class="headerlink" href="#streamreader-objects" title="本標題的永久連結">¶</a></h4>
<p>The <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> class is a subclass of <code class="xref py py-class docutils literal notranslate"><span class="pre">Codec</span></code> and defines the
following methods which every stream reader must define in order to be
compatible with the Python codec registry.</p>
<dl class="class">
<dt id="codecs.StreamReader">
<em class="property">class </em><code class="descclassname">codecs.</code><code class="descname">StreamReader</code><span class="sig-paren">(</span><em>stream</em>, <em>errors='strict'</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamReader" title="本定義的永久連結">¶</a></dt>
<dd><p>Constructor for a <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> instance.</p>
<p>All stream readers must provide this constructor interface. They are free to add
additional keyword arguments, but only the ones defined here are used by the
Python codec registry.</p>
<p>The <em>stream</em> argument must be a file-like object open for reading
text or binary data, as appropriate for the specific codec.</p>
<p>The <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> may implement different error handling schemes by
providing the <em>errors</em> keyword argument. See <a class="reference internal" href="#error-handlers"><span class="std std-ref">Error Handlers</span></a> for
the standard error handlers the underlying stream codec may support.</p>
<p>The <em>errors</em> argument will be assigned to an attribute of the same name.
Assigning to this attribute makes it possible to switch between different error
handling strategies during the lifetime of the <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> object.</p>
<p>The set of allowed values for the <em>errors</em> argument can be extended with
<a class="reference internal" href="#codecs.register_error" title="codecs.register_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">register_error()</span></code></a>.</p>
<dl class="method">
<dt id="codecs.StreamReader.read">
<code class="descname">read</code><span class="sig-paren">(</span><span class="optional">[</span><em>size</em><span class="optional">[</span>, <em>chars</em><span class="optional">[</span>, <em>firstline</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamReader.read" title="本定義的永久連結">¶</a></dt>
<dd><p>Decodes data from the stream and returns the resulting object.</p>
<p>The <em>chars</em> argument indicates the number of decoded
code points or bytes to return. The <a class="reference internal" href="#codecs.StreamReader.read" title="codecs.StreamReader.read"><code class="xref py py-func docutils literal notranslate"><span class="pre">read()</span></code></a> method will
never return more data than requested, but it might return less,
if there is not enough available.</p>
<p>The <em>size</em> argument indicates the approximate maximum
number of encoded bytes or code points to read
for decoding. The decoder can modify this setting as
appropriate. The default value -1 indicates to read and decode as much as
possible. This parameter is intended to
prevent having to decode huge files in one step.</p>
<p>The <em>firstline</em> flag indicates that
it would be sufficient to only return the first
line, if there are decoding errors on later lines.</p>
<p>The method should use a greedy read strategy meaning that it should read
as much data as is allowed within the definition of the encoding and the
given size, e.g. if optional encoding endings or state markers are
available on the stream, these should be read too.</p>
</dd></dl>
<dl class="method">
<dt id="codecs.StreamReader.readline">
<code class="descname">readline</code><span class="sig-paren">(</span><span class="optional">[</span><em>size</em><span class="optional">[</span>, <em>keepends</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamReader.readline" title="本定義的永久連結">¶</a></dt>
<dd><p>Read one line from the input stream and return the decoded data.</p>
<p><em>size</em>, if given, is passed as size argument to the stream’s
<a class="reference internal" href="#codecs.StreamReader.read" title="codecs.StreamReader.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> method.</p>
<p>If <em>keepends</em> is false line-endings will be stripped from the lines
returned.</p>
</dd></dl>
<dl class="method">
<dt id="codecs.StreamReader.readlines">
<code class="descname">readlines</code><span class="sig-paren">(</span><span class="optional">[</span><em>sizehint</em><span class="optional">[</span>, <em>keepends</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamReader.readlines" title="本定義的永久連結">¶</a></dt>
<dd><p>Read all lines available on the input stream and return them as a list of
lines.</p>
<p>Line-endings are implemented using the codec’s decoder method and are
included in the list entries if <em>keepends</em> is true.</p>
<p><em>sizehint</em>, if given, is passed as the <em>size</em> argument to the stream’s
<a class="reference internal" href="#codecs.StreamReader.read" title="codecs.StreamReader.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> method.</p>
</dd></dl>
<dl class="method">
<dt id="codecs.StreamReader.reset">
<code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamReader.reset" title="本定義的永久連結">¶</a></dt>
<dd><p>Resets the codec buffers used for keeping state.</p>
<p>Note that no stream repositioning should take place. This method is
primarily intended to be able to recover from decoding errors.</p>
</dd></dl>
</dd></dl>
<p>In addition to the above methods, the <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> must also inherit
all other methods and attributes from the underlying stream.</p>
</div>
<div class="section" id="streamreaderwriter-objects">
<span id="stream-reader-writer"></span><h4>7.2.1.4.3. StreamReaderWriter Objects<a class="headerlink" href="#streamreaderwriter-objects" title="本標題的永久連結">¶</a></h4>
<p>The <a class="reference internal" href="#codecs.StreamReaderWriter" title="codecs.StreamReaderWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReaderWriter</span></code></a> is a convenience class that allows wrapping
streams which work in both read and write modes.</p>
<p>The design is such that one can use the factory functions returned by the
<a class="reference internal" href="#codecs.lookup" title="codecs.lookup"><code class="xref py py-func docutils literal notranslate"><span class="pre">lookup()</span></code></a> function to construct the instance.</p>
<dl class="class">
<dt id="codecs.StreamReaderWriter">
<em class="property">class </em><code class="descclassname">codecs.</code><code class="descname">StreamReaderWriter</code><span class="sig-paren">(</span><em>stream</em>, <em>Reader</em>, <em>Writer</em>, <em>errors='strict'</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamReaderWriter" title="本定義的永久連結">¶</a></dt>
<dd><p>Creates a <a class="reference internal" href="#codecs.StreamReaderWriter" title="codecs.StreamReaderWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReaderWriter</span></code></a> instance. <em>stream</em> must be a file-like
object. <em>Reader</em> and <em>Writer</em> must be factory functions or classes providing the
<a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> and <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> interface resp. Error handling
is done in the same way as defined for the stream readers and writers.</p>
</dd></dl>
<p><a class="reference internal" href="#codecs.StreamReaderWriter" title="codecs.StreamReaderWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReaderWriter</span></code></a> instances define the combined interfaces of
<a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> and <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> classes. They inherit all other
methods and attributes from the underlying stream.</p>
</div>
<div class="section" id="streamrecoder-objects">
<span id="stream-recoder-objects"></span><h4>7.2.1.4.4. StreamRecoder Objects<a class="headerlink" href="#streamrecoder-objects" title="本標題的永久連結">¶</a></h4>
<p>The <a class="reference internal" href="#codecs.StreamRecoder" title="codecs.StreamRecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamRecoder</span></code></a> translates data from one encoding to another,
which is sometimes useful when dealing with different encoding environments.</p>
<p>The design is such that one can use the factory functions returned by the
<a class="reference internal" href="#codecs.lookup" title="codecs.lookup"><code class="xref py py-func docutils literal notranslate"><span class="pre">lookup()</span></code></a> function to construct the instance.</p>
<dl class="class">
<dt id="codecs.StreamRecoder">
<em class="property">class </em><code class="descclassname">codecs.</code><code class="descname">StreamRecoder</code><span class="sig-paren">(</span><em>stream</em>, <em>encode</em>, <em>decode</em>, <em>Reader</em>, <em>Writer</em>, <em>errors='strict'</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamRecoder" title="本定義的永久連結">¶</a></dt>
<dd><p>Creates a <a class="reference internal" href="#codecs.StreamRecoder" title="codecs.StreamRecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamRecoder</span></code></a> instance which implements a two-way conversion:
<em>encode</em> and <em>decode</em> work on the frontend — the data visible to
code calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code>, while <em>Reader</em> and <em>Writer</em>
work on the backend — the data in <em>stream</em>.</p>
<p>You can use these objects to do transparent transcodings from e.g. Latin-1
to UTF-8 and back.</p>
<p>The <em>stream</em> argument must be a file-like object.</p>
<p>The <em>encode</em> and <em>decode</em> arguments must
adhere to the <code class="xref py py-class docutils literal notranslate"><span class="pre">Codec</span></code> interface. <em>Reader</em> and
<em>Writer</em> must be factory functions or classes providing objects of the
<a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> and <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> interface respectively.</p>
<p>Error handling is done in the same way as defined for the stream readers and
writers.</p>
</dd></dl>
<p><a class="reference internal" href="#codecs.StreamRecoder" title="codecs.StreamRecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamRecoder</span></code></a> instances define the combined interfaces of
<a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> and <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> classes. They inherit all other
methods and attributes from the underlying stream.</p>
</div>
</div>
</div>
<div class="section" id="encodings-and-unicode">
<span id="encodings-overview"></span><h2>7.2.2. Encodings and Unicode<a class="headerlink" href="#encodings-and-unicode" title="本標題的永久連結">¶</a></h2>
<p>Strings are stored internally as sequences of code points in
range <code class="docutils literal notranslate"><span class="pre">0x0</span></code>–<code class="docutils literal notranslate"><span class="pre">0x10FFFF</span></code>. (See <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0393"><strong>PEP 393</strong></a> for
more details about the implementation.)
Once a string object is used outside of CPU and memory, endianness
and how these arrays are stored as bytes become an issue. As with other
codecs, serialising a string into a sequence of bytes is known as <em>encoding</em>,
and recreating the string from the sequence of bytes is known as <em>decoding</em>.
There are a variety of different text serialisation codecs, which are
collectivity referred to as <a class="reference internal" href="../glossary.html#term-text-encoding"><span class="xref std std-term">text encodings</span></a>.</p>
<p>The simplest text encoding (called <code class="docutils literal notranslate"><span class="pre">'latin-1'</span></code> or <code class="docutils literal notranslate"><span class="pre">'iso-8859-1'</span></code>) maps
the code points 0–255 to the bytes <code class="docutils literal notranslate"><span class="pre">0x0</span></code>–<code class="docutils literal notranslate"><span class="pre">0xff</span></code>, which means that a string
object that contains code points above <code class="docutils literal notranslate"><span class="pre">U+00FF</span></code> can’t be encoded with this
codec. Doing so will raise a <a class="reference internal" href="exceptions.html#UnicodeEncodeError" title="UnicodeEncodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code></a> that looks
like the following (although the details of the error message may differ):
<code class="docutils literal notranslate"><span class="pre">UnicodeEncodeError:</span> <span class="pre">'latin-1'</span> <span class="pre">codec</span> <span class="pre">can't</span> <span class="pre">encode</span> <span class="pre">character</span> <span class="pre">'\u1234'</span> <span class="pre">in</span>
<span class="pre">position</span> <span class="pre">3:</span> <span class="pre">ordinal</span> <span class="pre">not</span> <span class="pre">in</span> <span class="pre">range(256)</span></code>.</p>
<p>There’s another group of encodings (the so called charmap encodings) that choose
a different subset of all Unicode code points and how these code points are
mapped to the bytes <code class="docutils literal notranslate"><span class="pre">0x0</span></code>–<code class="docutils literal notranslate"><span class="pre">0xff</span></code>. To see how this is done simply open
e.g. <code class="file docutils literal notranslate"><span class="pre">encodings/cp1252.py</span></code> (which is an encoding that is used primarily on
Windows). There’s a string constant with 256 characters that shows you which
character is mapped to which byte value.</p>
<p>All of these encodings can only encode 256 of the 1114112 code points
defined in Unicode. A simple and straightforward way that can store each Unicode
code point, is to store each code point as four consecutive bytes. There are two
possibilities: store the bytes in big endian or in little endian order. These
two encodings are called <code class="docutils literal notranslate"><span class="pre">UTF-32-BE</span></code> and <code class="docutils literal notranslate"><span class="pre">UTF-32-LE</span></code> respectively. Their
disadvantage is that if e.g. you use <code class="docutils literal notranslate"><span class="pre">UTF-32-BE</span></code> on a little endian machine you
will always have to swap bytes on encoding and decoding. <code class="docutils literal notranslate"><span class="pre">UTF-32</span></code> avoids this
problem: bytes will always be in natural endianness. When these bytes are read
by a CPU with a different endianness, then bytes have to be swapped though. To
be able to detect the endianness of a <code class="docutils literal notranslate"><span class="pre">UTF-16</span></code> or <code class="docutils literal notranslate"><span class="pre">UTF-32</span></code> byte sequence,
there’s the so called BOM (「Byte Order Mark」). This is the Unicode character
<code class="docutils literal notranslate"><span class="pre">U+FEFF</span></code>. This character can be prepended to every <code class="docutils literal notranslate"><span class="pre">UTF-16</span></code> or <code class="docutils literal notranslate"><span class="pre">UTF-32</span></code>
byte sequence. The byte swapped version of this character (<code class="docutils literal notranslate"><span class="pre">0xFFFE</span></code>) is an
illegal character that may not appear in a Unicode text. So when the
first character in an <code class="docutils literal notranslate"><span class="pre">UTF-16</span></code> or <code class="docutils literal notranslate"><span class="pre">UTF-32</span></code> byte sequence
appears to be a <code class="docutils literal notranslate"><span class="pre">U+FFFE</span></code> the bytes have to be swapped on decoding.
Unfortunately the character <code class="docutils literal notranslate"><span class="pre">U+FEFF</span></code> had a second purpose as
a <code class="docutils literal notranslate"><span class="pre">ZERO</span> <span class="pre">WIDTH</span> <span class="pre">NO-BREAK</span> <span class="pre">SPACE</span></code>: a character that has no width and doesn’t allow
a word to be split. It can e.g. be used to give hints to a ligature algorithm.
With Unicode 4.0 using <code class="docutils literal notranslate"><span class="pre">U+FEFF</span></code> as a <code class="docutils literal notranslate"><span class="pre">ZERO</span> <span class="pre">WIDTH</span> <span class="pre">NO-BREAK</span> <span class="pre">SPACE</span></code> has been
deprecated (with <code class="docutils literal notranslate"><span class="pre">U+2060</span></code> (<code class="docutils literal notranslate"><span class="pre">WORD</span> <span class="pre">JOINER</span></code>) assuming this role). Nevertheless
Unicode software still must be able to handle <code class="docutils literal notranslate"><span class="pre">U+FEFF</span></code> in both roles: as a BOM
it’s a device to determine the storage layout of the encoded bytes, and vanishes
once the byte sequence has been decoded into a string; as a <code class="docutils literal notranslate"><span class="pre">ZERO</span> <span class="pre">WIDTH</span>
<span class="pre">NO-BREAK</span> <span class="pre">SPACE</span></code> it’s a normal character that will be decoded like any other.</p>
<p>There’s another encoding that is able to encoding the full range of Unicode
characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
parts: marker bits (the most significant bits) and payload bits. The marker bits
are a sequence of zero to four <code class="docutils literal notranslate"><span class="pre">1</span></code> bits followed by a <code class="docutils literal notranslate"><span class="pre">0</span></code> bit. Unicode characters are
encoded like this (with x being payload bits, which when concatenated give the
Unicode character):</p>
<table border="1" class="docutils">
<colgroup>
<col width="43%" />
<col width="57%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Range</th>
<th class="head">Encoding</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">U-00000000</span></code> … <code class="docutils literal notranslate"><span class="pre">U-0000007F</span></code></td>
<td>0xxxxxxx</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">U-00000080</span></code> … <code class="docutils literal notranslate"><span class="pre">U-000007FF</span></code></td>
<td>110xxxxx 10xxxxxx</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">U-00000800</span></code> … <code class="docutils literal notranslate"><span class="pre">U-0000FFFF</span></code></td>
<td>1110xxxx 10xxxxxx 10xxxxxx</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">U-00010000</span></code> … <code class="docutils literal notranslate"><span class="pre">U-0010FFFF</span></code></td>
<td>11110xxx 10xxxxxx 10xxxxxx 10xxxxxx</td>
</tr>
</tbody>
</table>
<p>The least significant bit of the Unicode character is the rightmost x bit.</p>
<p>As UTF-8 is an 8-bit encoding no BOM is required and any <code class="docutils literal notranslate"><span class="pre">U+FEFF</span></code> character in
the decoded string (even if it’s the first character) is treated as a <code class="docutils literal notranslate"><span class="pre">ZERO</span>
<span class="pre">WIDTH</span> <span class="pre">NO-BREAK</span> <span class="pre">SPACE</span></code>.</p>
<p>Without external information it’s impossible to reliably determine which
encoding was used for encoding a string. Each charmap encoding can
decode any random byte sequence. However that’s not possible with UTF-8, as
UTF-8 byte sequences have a structure that doesn’t allow arbitrary byte