-
Notifications
You must be signed in to change notification settings - Fork 3
/
inputoutput.html
1075 lines (1074 loc) · 40.4 KB
/
inputoutput.html
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>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=yes"
/>
<title>inputoutput</title>
<style type="text/css">
code {
white-space: pre-wrap;
}
span.smallcaps {
font-variant: small-caps;
}
span.underline {
text-decoration: underline;
}
div.column {
display: inline-block;
vertical-align: top;
width: 50%;
}
</style>
</head>
<body>
<h3 id="navigation">Navigation</h3>
<ul>
<li>
<a href="https://docs.python.org/3/genindex.html" title="General Index"
>index</a
>
</li>
<li>
<a
href="https://docs.python.org/3/py-modindex.html"
title="Python Module Index"
>modules</a
>
|
</li>
<li><a href="errors.html" title="8. Errors and Exceptions">next</a> |</li>
<li><a href="modules.html" title="6. Modules">previous</a> |</li>
<li><img src="../_static/py.png" /></li>
<li><a href="https://www.python.org/">Python</a> »</li>
<li>
<a href="https://docs.python.org/3/index.html">3.9.5 Documentation</a> »
</li>
<li><a href="index.html">The Python Tutorial</a> »</li>
<li></li>
</ul>
<p><span id="tut-io"></span></p>
<h1 id="input-and-output">
<span class="section-number">7. </span>Input and Output<a
href="#input-and-output"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h1>
<p>
There are several ways to present the output of a program; data can be
printed in a human-readable form, or written to a file for future use.
This chapter will discuss some of the possibilities.
</p>
<p><span id="tut-formatting"></span></p>
<h2 id="fancier-output-formatting">
<span class="section-number">7.1. </span>Fancier Output Formatting<a
href="#fancier-output-formatting"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
So far we’ve encountered two ways of writing values:
<em>expression statements</em> and the
<a
href="https://docs.python.org/3/library/functions.html#print"
class="reference internal"
title="print"
><code class="sourceCode python"
><span class="bu">print</span>()</code
></a
>
function. (A third way is using the <code>write()</code> method of file
objects; the standard output file can be referenced as
<code>sys.stdout</code>. See the Library Reference for more information on
this.)
</p>
<p>
Often you’ll want more control over the formatting of your output than
simply printing space-separated values. There are several ways to format
output.
</p>
<ul>
<li>
<p>
To use
<a href="#tut-f-strings" class="reference internal"
><span class="std std-ref">formatted string literals</span></a
>, begin a string with <code>f</code> or <code>F</code> before the
opening quotation mark or triple quotation mark. Inside this string,
you can write a Python expression between <code>{</code> and
<code>}</code> characters that can refer to variables or literal
values.
</p>
<pre><code>>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'</code></pre>
</li>
<li>
<p>
The
<a
href="https://docs.python.org/3/library/stdtypes.html#str.format"
class="reference internal"
title="str.format"
><code class="sourceCode python"
><span class="bu">str</span>.<span class="bu">format</span
>()</code
></a
>
method of strings requires more manual effort. You’ll still use
<code>{</code> and <code>}</code> to mark where a variable will be
substituted and can provide detailed formatting directives, but you’ll
also need to provide the information to be formatted.
</p>
<pre><code>>>> yes_votes = 42_572_654
>>> no_votes = 43_132_495
>>> percentage = yes_votes / (yes_votes + no_votes)
>>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)
' 42572654 YES votes 49.67%'</code></pre>
</li>
<li>
<p>
Finally, you can do all the string handling yourself by using string
slicing and concatenation operations to create any layout you can
imagine. The string type has some methods that perform useful
operations for padding strings to a given column width.
</p>
</li>
</ul>
<p>
When you don’t need fancy output but just want a quick display of some
variables for debugging purposes, you can convert any value to a string
with the
<a
href="https://docs.python.org/3/library/functions.html#repr"
class="reference internal"
title="repr"
><code class="sourceCode python"
><span class="bu">repr</span>()</code
></a
>
or
<a
href="https://docs.python.org/3/library/stdtypes.html#str"
class="reference internal"
title="str"
><code class="sourceCode python"><span class="bu">str</span>()</code></a
>
functions.
</p>
<p>
The
<a
href="https://docs.python.org/3/library/stdtypes.html#str"
class="reference internal"
title="str"
><code class="sourceCode python"><span class="bu">str</span>()</code></a
>
function is meant to return representations of values which are fairly
human-readable, while
<a
href="https://docs.python.org/3/library/functions.html#repr"
class="reference internal"
title="repr"
><code class="sourceCode python"
><span class="bu">repr</span>()</code
></a
>
is meant to generate representations which can be read by the interpreter
(or will force a
<a
href="https://docs.python.org/3/library/exceptions.html#SyntaxError"
class="reference internal"
title="SyntaxError"
><code class="sourceCode python"
><span class="pp">SyntaxError</span></code
></a
>
if there is no equivalent syntax). For objects which don’t have a
particular representation for human consumption,
<a
href="https://docs.python.org/3/library/stdtypes.html#str"
class="reference internal"
title="str"
><code class="sourceCode python"><span class="bu">str</span>()</code></a
>
will return the same value as
<a
href="https://docs.python.org/3/library/functions.html#repr"
class="reference internal"
title="repr"
><code class="sourceCode python"
><span class="bu">repr</span>()</code
></a
>. Many values, such as numbers or structures like lists and dictionaries,
have the same representation using either function. Strings, in
particular, have two distinct representations.
</p>
<p>Some examples:</p>
<pre><code>>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print(s)
The value of x is 32.5, and y is 40000...
>>> # The repr() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # The argument to repr() may be any Python object:
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"</code></pre>
<p>
The
<a
href="https://docs.python.org/3/library/string.html#module-string"
class="reference internal"
title="string: Common string operations."
><code class="sourceCode python">string</code></a
>
module contains a
<a
href="https://docs.python.org/3/library/string.html#string.Template"
class="reference internal"
title="string.Template"
><code class="sourceCode python">Template</code></a
>
class that offers yet another way to substitute values into strings, using
placeholders like <code>$x</code> and replacing them with values from a
dictionary, but offers much less control of the formatting.
</p>
<p><span id="tut-f-strings"></span></p>
<h3 id="formatted-string-literals">
<span class="section-number">7.1.1. </span>Formatted String Literals<a
href="#formatted-string-literals"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h3>
<p>
<a
href="https://docs.python.org/3/reference/lexical_analysis.html#f-strings"
class="reference internal"
><span class="std std-ref">Formatted string literals</span></a
>
(also called f-strings for short) let you include the value of Python
expressions inside a string by prefixing the string with <code>f</code> or
<code>F</code> and writing expressions as <code>{expression}</code>.
</p>
<p>
An optional format specifier can follow the expression. This allows
greater control over how the value is formatted. The following example
rounds pi to three places after the decimal:
</p>
<pre><code>>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.</code></pre>
<p>
Passing an integer after the <code>':'</code> will cause that field to be
a minimum number of characters wide. This is useful for making columns
line up.
</p>
<pre><code>>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print(f'{name:10} ==> {phone:10d}')
...
Sjoerd ==> 4127
Jack ==> 4098
Dcab ==> 7678</code></pre>
<p>
Other modifiers can be used to convert the value before it is formatted.
<code>'!a'</code> applies
<a
href="https://docs.python.org/3/library/functions.html#ascii"
class="reference internal"
title="ascii"
><code class="sourceCode python"
><span class="bu">ascii</span>()</code
></a
>, <code>'!s'</code> applies
<a
href="https://docs.python.org/3/library/stdtypes.html#str"
class="reference internal"
title="str"
><code class="sourceCode python"><span class="bu">str</span>()</code></a
>, and <code>'!r'</code> applies
<a
href="https://docs.python.org/3/library/functions.html#repr"
class="reference internal"
title="repr"
><code class="sourceCode python"
><span class="bu">repr</span>()</code
></a
>:
</p>
<pre><code>>>> animals = 'eels'
>>> print(f'My hovercraft is full of {animals}.')
My hovercraft is full of eels.
>>> print(f'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.</code></pre>
<p>
For a reference on these format specifications, see the reference guide
for the
<a
href="https://docs.python.org/3/library/string.html#formatspec"
class="reference internal"
><span class="std std-ref">Format Specification Mini-Language</span></a
>.
</p>
<p><span id="tut-string-format"></span></p>
<h3 id="the-string-format-method">
<span class="section-number">7.1.2. </span>The String format() Method<a
href="#the-string-format-method"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h3>
<p>
Basic usage of the
<a
href="https://docs.python.org/3/library/stdtypes.html#str.format"
class="reference internal"
title="str.format"
><code class="sourceCode python"
><span class="bu">str</span>.<span class="bu">format</span>()</code
></a
>
method looks like this:
</p>
<pre><code>>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"</code></pre>
<p>
The brackets and characters within them (called format fields) are
replaced with the objects passed into the
<a
href="https://docs.python.org/3/library/stdtypes.html#str.format"
class="reference internal"
title="str.format"
><code class="sourceCode python"
><span class="bu">str</span>.<span class="bu">format</span>()</code
></a
>
method. A number in the brackets can be used to refer to the position of
the object passed into the
<a
href="https://docs.python.org/3/library/stdtypes.html#str.format"
class="reference internal"
title="str.format"
><code class="sourceCode python"
><span class="bu">str</span>.<span class="bu">format</span>()</code
></a
>
method.
</p>
<pre><code>>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam</code></pre>
<p>
If keyword arguments are used in the
<a
href="https://docs.python.org/3/library/stdtypes.html#str.format"
class="reference internal"
title="str.format"
><code class="sourceCode python"
><span class="bu">str</span>.<span class="bu">format</span>()</code
></a
>
method, their values are referred to by using the name of the argument.
</p>
<pre><code>>>> print('This {food} is {adjective}.'.format(
... food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.</code></pre>
<p>Positional and keyword arguments can be arbitrarily combined:</p>
<pre><code>>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
other='Georg'))
The story of Bill, Manfred, and Georg.</code></pre>
<p>
If you have a really long format string that you don’t want to split up,
it would be nice if you could reference the variables to be formatted by
name instead of by position. This can be done by simply passing the dict
and using square brackets <code>'[]'</code> to access the keys.
</p>
<pre><code>>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
... 'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678</code></pre>
<p>
This could also be done by passing the table as keyword arguments with the
‘**’ notation.
</p>
<pre><code>>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678</code></pre>
<p>
This is particularly useful in combination with the built-in function
<a
href="https://docs.python.org/3/library/functions.html#vars"
class="reference internal"
title="vars"
><code class="sourceCode python"
><span class="bu">vars</span>()</code
></a
>, which returns a dictionary containing all local variables.
</p>
<p>
As an example, the following lines produce a tidily-aligned set of columns
giving integers and their squares and cubes:
</p>
<pre><code>>>> for x in range(1, 11):
... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000</code></pre>
<p>
For a complete overview of string formatting with
<a
href="https://docs.python.org/3/library/stdtypes.html#str.format"
class="reference internal"
title="str.format"
><code class="sourceCode python"
><span class="bu">str</span>.<span class="bu">format</span>()</code
></a
>, see
<a
href="https://docs.python.org/3/library/string.html#formatstrings"
class="reference internal"
><span class="std std-ref">Format String Syntax</span></a
>.
</p>
<h3 id="manual-string-formatting">
<span class="section-number">7.1.3. </span>Manual String Formatting<a
href="#manual-string-formatting"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h3>
<p>Here’s the same table of squares and cubes, formatted manually:</p>
<pre><code>>>> for x in range(1, 11):
... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
... # Note use of 'end' on previous line
... print(repr(x*x*x).rjust(4))
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000</code></pre>
<p>
(Note that the one space between each column was added by the way
<a
href="https://docs.python.org/3/library/functions.html#print"
class="reference internal"
title="print"
><code class="sourceCode python"
><span class="bu">print</span>()</code
></a
>
works: it always adds spaces between its arguments.)
</p>
<p>
The
<a
href="https://docs.python.org/3/library/stdtypes.html#str.rjust"
class="reference internal"
title="str.rjust"
><code class="sourceCode python"
><span class="bu">str</span>.rjust()</code
></a
>
method of string objects right-justifies a string in a field of a given
width by padding it with spaces on the left. There are similar methods
<a
href="https://docs.python.org/3/library/stdtypes.html#str.ljust"
class="reference internal"
title="str.ljust"
><code class="sourceCode python"
><span class="bu">str</span>.ljust()</code
></a
>
and
<a
href="https://docs.python.org/3/library/stdtypes.html#str.center"
class="reference internal"
title="str.center"
><code class="sourceCode python"
><span class="bu">str</span>.center()</code
></a
>. These methods do not write anything, they just return a new string. If
the input string is too long, they don’t truncate it, but return it
unchanged; this will mess up your column lay-out but that’s usually better
than the alternative, which would be lying about a value. (If you really
want truncation you can always add a slice operation, as in
<code>x.ljust(n)[:n]</code>.)
</p>
<p>
There is another method,
<a
href="https://docs.python.org/3/library/stdtypes.html#str.zfill"
class="reference internal"
title="str.zfill"
><code class="sourceCode python"
><span class="bu">str</span>.zfill()</code
></a
>, which pads a numeric string on the left with zeros. It understands
about plus and minus signs:
</p>
<pre><code>>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'</code></pre>
<h3 id="old-string-formatting">
<span class="section-number">7.1.4. </span>Old string formatting<a
href="#old-string-formatting"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h3>
<p>
The % operator (modulo) can also be used for string formatting. Given
<code>'string' % values</code>, instances of <code>%</code> in
<code>string</code> are replaced with zero or more elements of
<code>values</code>. This operation is commonly known as string
interpolation. For example:
</p>
<pre><code>>>> import math
>>> print('The value of pi is approximately %5.3f.' % math.pi)
The value of pi is approximately 3.142.</code></pre>
<p>
More information can be found in the
<a
href="https://docs.python.org/3/library/stdtypes.html#old-string-formatting"
class="reference internal"
><span class="std std-ref">printf-style String Formatting</span></a
>
section.
</p>
<p><span id="tut-files"></span></p>
<h2 id="reading-and-writing-files">
<span class="section-number">7.2. </span>Reading and Writing Files<a
href="#reading-and-writing-files"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
<a
href="https://docs.python.org/3/library/functions.html#open"
class="reference internal"
title="open"
><code class="sourceCode python"
><span class="bu">open</span>()</code
></a
>
returns a
<a
href="https://docs.python.org/3/glossary.html#term-file-object"
class="reference internal"
><span class="xref std std-term">file object</span></a
>, and is most commonly used with two arguments:
<code>open(filename, mode)</code>.
</p>
<pre><code>>>> f = open('workfile', 'w')</code></pre>
<p>
The first argument is a string containing the filename. The second
argument is another string containing a few characters describing the way
in which the file will be used. <em>mode</em> can be <code>'r'</code> when
the file will only be read, <code>'w'</code> for only writing (an existing
file with the same name will be erased), and <code>'a'</code> opens the
file for appending; any data written to the file is automatically added to
the end. <code>'r+'</code> opens the file for both reading and writing.
The <em>mode</em> argument is optional; <code>'r'</code> will be assumed
if it’s omitted.
</p>
<p>
Normally, files are opened in <em>text mode</em>, that means, you read and
write strings from and to the file, which are encoded in a specific
encoding. If encoding is not specified, the default is platform dependent
(see
<a
href="https://docs.python.org/3/library/functions.html#open"
class="reference internal"
title="open"
><code class="sourceCode python"
><span class="bu">open</span>()</code
></a
>). <code>'b'</code> appended to the mode opens the file in
<em>binary mode</em>: now the data is read and written in the form of
bytes objects. This mode should be used for all files that don’t contain
text.
</p>
<p>
In text mode, the default when reading is to convert platform-specific
line endings (<code>\n</code> on Unix, <code>\r\n</code> on Windows) to
just <code>\n</code>. When writing in text mode, the default is to convert
occurrences of <code>\n</code> back to platform-specific line endings.
This behind-the-scenes modification to file data is fine for text files,
but will corrupt binary data like that in <code>JPEG</code> or
<code>EXE</code> files. Be very careful to use binary mode when reading
and writing such files.
</p>
<p>
It is good practice to use the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#with"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>with</code
></a
>
keyword when dealing with file objects. The advantage is that the file is
properly closed after its suite finishes, even if an exception is raised
at some point. Using <code>with</code> is also much shorter than writing
equivalent
<a
href="https://docs.python.org/3/reference/compound_stmts.html#try"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>try</code
></a
>-<a
href="https://docs.python.org/3/reference/compound_stmts.html#finally"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>finally</code
></a
>
blocks:
</p>
<pre><code>>>> with open('workfile') as f:
... read_data = f.read()
>>> # We can check that the file has been automatically closed.
>>> f.closed
True</code></pre>
<p>
If you’re not using the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#with"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>with</code
></a
>
keyword, then you should call <code>f.close()</code> to close the file and
immediately free up any system resources used by it.
</p>
<p>Warning</p>
<p>
Calling <code>f.write()</code> without using the <code>with</code> keyword
or calling <code>f.close()</code> <strong>might</strong> result in the
arguments of <code>f.write()</code> not being completely written to the
disk, even if the program exits successfully.
</p>
<p>
After a file object is closed, either by a
<a
href="https://docs.python.org/3/reference/compound_stmts.html#with"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>with</code
></a
>
statement or by calling <code>f.close()</code>, attempts to use the file
object will automatically fail.
</p>
<pre><code>>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.</code></pre>
<p><span id="tut-filemethods"></span></p>
<h3 id="methods-of-file-objects">
<span class="section-number">7.2.1. </span>Methods of File Objects<a
href="#methods-of-file-objects"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h3>
<p>
The rest of the examples in this section will assume that a file object
called <code>f</code> has already been created.
</p>
<p>
To read a file’s contents, call <code>f.read(size)</code>, which reads
some quantity of data and returns it as a string (in text mode) or bytes
object (in binary mode). <em>size</em> is an optional numeric argument.
When <em>size</em> is omitted or negative, the entire contents of the file
will be read and returned; it’s your problem if the file is twice as large
as your machine’s memory. Otherwise, at most <em>size</em> characters (in
text mode) or <em>size</em> bytes (in binary mode) are read and returned.
If the end of the file has been reached, <code>f.read()</code> will return
an empty string (<code>''</code>).
</p>
<pre><code>>>> f.read()
'This is the entire file.\n'
>>> f.read()
''</code></pre>
<p>
<code>f.readline()</code> reads a single line from the file; a newline
character (<code>\n</code>) is left at the end of the string, and is only
omitted on the last line of the file if the file doesn’t end in a newline.
This makes the return value unambiguous; if
<code>f.readline()</code> returns an empty string, the end of the file has
been reached, while a blank line is represented by <code>'\n'</code>, a
string containing only a single newline.
</p>
<pre><code>>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''</code></pre>
<p>
For reading lines from a file, you can loop over the file object. This is
memory efficient, fast, and leads to simple code:
</p>
<pre><code>>>> for line in f:
... print(line, end='')
...
This is the first line of the file.
Second line of the file</code></pre>
<p>
If you want to read all the lines of a file in a list you can also use
<code>list(f)</code> or <code>f.readlines()</code>.
</p>
<p>
<code>f.write(string)</code> writes the contents of <em>string</em> to the
file, returning the number of characters written.
</p>
<pre><code>>>> f.write('This is a test\n')
15</code></pre>
<p>
Other types of objects need to be converted – either to a string (in text
mode) or a bytes object (in binary mode) – before writing them:
</p>
<pre><code>>>> value = ('the answer', 42)
>>> s = str(value) # convert the tuple to string
>>> f.write(s)
18</code></pre>
<p>
<code>f.tell()</code> returns an integer giving the file object’s current
position in the file represented as number of bytes from the beginning of
the file when in binary mode and an opaque number when in text mode.
</p>
<p>
To change the file object’s position, use
<code>f.seek(offset, whence)</code>. The position is computed from adding
<em>offset</em> to a reference point; the reference point is selected by
the <em>whence</em> argument. A <em>whence</em> value of 0 measures from
the beginning of the file, 1 uses the current file position, and 2 uses
the end of the file as the reference point. <em>whence</em> can be omitted
and defaults to 0, using the beginning of the file as the reference point.
</p>
<pre><code>>>> f = open('workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5) # Go to the 6th byte in the file
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2) # Go to the 3rd byte before the end
13
>>> f.read(1)
b'd'</code></pre>
<p>
In text files (those opened without a <code>b</code> in the mode string),
only seeks relative to the beginning of the file are allowed (the
exception being seeking to the very file end with <code>seek(0, 2)</code>)
and the only valid <em>offset</em> values are those returned from the
<code>f.tell()</code>, or zero. Any other <em>offset</em> value produces
undefined behaviour.
</p>
<p>
File objects have some additional methods, such as
<code>isatty()</code> and <code>truncate()</code> which are less
frequently used; consult the Library Reference for a complete guide to
file objects.
</p>
<p><span id="tut-json"></span></p>
<h3 id="saving-structured-data-with-json">
<span class="section-number">7.2.2. </span>Saving structured data with
<a
href="https://docs.python.org/3/library/json.html#module-json"
class="reference internal"
title="json: Encode and decode the JSON format."
><code class="sourceCode python">json</code></a
><a
href="#saving-structured-data-with-json"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h3>
<p>
Strings can easily be written to and read from a file. Numbers take a bit
more effort, since the <code>read()</code> method only returns strings,
which will have to be passed to a function like
<a
href="https://docs.python.org/3/library/functions.html#int"
class="reference internal"
title="int"
><code class="sourceCode python"><span class="bu">int</span>()</code></a
>, which takes a string like <code>'123'</code> and returns its numeric
value 123. When you want to save more complex data types like nested lists
and dictionaries, parsing and serializing by hand becomes complicated.
</p>
<p>
Rather than having users constantly writing and debugging code to save
complicated data types to files, Python allows you to use the popular data
interchange format called
<a href="http://json.org/" class="reference external"
>JSON (JavaScript Object Notation)</a
>. The standard module called
<a
href="https://docs.python.org/3/library/json.html#module-json"
class="reference internal"
title="json: Encode and decode the JSON format."
><code class="sourceCode python">json</code></a
>
can take Python data hierarchies, and convert them to string
representations; this process is called <em>serializing</em>.
Reconstructing the data from the string representation is called
<em>deserializing</em>. Between serializing and deserializing, the string
representing the object may have been stored in a file or data, or sent
over a network connection to some distant machine.
</p>
<p>Note</p>
<p>
The JSON format is commonly used by modern applications to allow for data
exchange. Many programmers are already familiar with it, which makes it a
good choice for interoperability.
</p>
<p>
If you have an object <code>x</code>, you can view its JSON string
representation with a simple line of code:
</p>
<pre><code>>>> import json
>>> x = [1, 'simple', 'list']
>>> json.dumps(x)
'[1, "simple", "list"]'</code></pre>
<p>
Another variant of the
<a
href="https://docs.python.org/3/library/json.html#json.dumps"
class="reference internal"
title="json.dumps"
><code class="sourceCode python">dumps()</code></a
>
function, called
<a
href="https://docs.python.org/3/library/json.html#json.dump"
class="reference internal"
title="json.dump"
><code class="sourceCode python">dump()</code></a
>, simply serializes the object to a
<a
href="https://docs.python.org/3/glossary.html#term-text-file"
class="reference internal"
><span class="xref std std-term">text file</span></a
>. So if <code>f</code> is a
<a
href="https://docs.python.org/3/glossary.html#term-text-file"
class="reference internal"
><span class="xref std std-term">text file</span></a
>
object opened for writing, we can do this:
</p>
<pre><code>json.dump(x, f)</code></pre>
<p>
To decode the object again, if <code>f</code> is a
<a
href="https://docs.python.org/3/glossary.html#term-text-file"
class="reference internal"
><span class="xref std std-term">text file</span></a
>
object which has been opened for reading:
</p>
<pre><code>x = json.load(f)</code></pre>
<p>
This simple serialization technique can handle lists and dictionaries, but
serializing arbitrary class instances in JSON requires a bit of extra
effort. The reference for the
<a
href="https://docs.python.org/3/library/json.html#module-json"
class="reference internal"
title="json: Encode and decode the JSON format."
><code class="sourceCode python">json</code></a
>
module contains an explanation of this.
</p>
<p>See also</p>
<p>
<a
href="https://docs.python.org/3/library/pickle.html#module-pickle"
class="reference internal"
title="pickle: Convert Python objects to streams of bytes and back."
><code class="sourceCode python">pickle</code></a
>
- the pickle module
</p>
<p>
Contrary to
<a href="#tut-json" class="reference internal"
><span class="std std-ref">JSON</span></a
>, <em>pickle</em> is a protocol which allows the serialization of
arbitrarily complex Python objects. As such, it is specific to Python and
cannot be used to communicate with applications written in other
languages. It is also insecure by default: deserializing pickle data
coming from an untrusted source can execute arbitrary code, if the data
was crafted by a skilled attacker.
</p>
<h3 id="table-of-contents">
<a href="https://docs.python.org/3/contents.html">Table of Contents</a>
</h3>
<ul>
<li>
<a href="#" class="reference internal">7. Input and Output</a>
<ul>
<li>
<a href="#fancier-output-formatting" class="reference internal"
>7.1. Fancier Output Formatting</a
>
<ul>
<li>
<a href="#formatted-string-literals" class="reference internal"
>7.1.1. Formatted String Literals</a
>
</li>
<li>
<a href="#the-string-format-method" class="reference internal"
>7.1.2. The String format() Method</a
>
</li>
<li>
<a href="#manual-string-formatting" class="reference internal"
>7.1.3. Manual String Formatting</a
>
</li>
<li>
<a href="#old-string-formatting" class="reference internal"
>7.1.4. Old string formatting</a
>
</li>
</ul>
</li>
<li>
<a href="#reading-and-writing-files" class="reference internal"
>7.2. Reading and Writing Files</a
>
<ul>
<li>
<a href="#methods-of-file-objects" class="reference internal"
>7.2.1. Methods of File Objects</a
>