Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 58f39f1

Browse files
khanhnnvngitbook-bot
authored andcommitted
GitBook: [master] 2 pages modified
1 parent c626a95 commit 58f39f1

2 files changed

Lines changed: 335 additions & 2 deletions

File tree

7.-input-and-output.md

Lines changed: 332 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,332 @@
1+
# 7. Input and Output
2+
3+
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.
4+
5+
### 7.1. Fancier Output Formatting
6+
7+
So far we’ve encountered two ways of writing values: _expression statements_ and the [`print()`](https://docs.python.org/3/library/functions.html#print) function. \(A third way is using the `write()` method of file objects; the standard output file can be referenced as `sys.stdout`. See the Library Reference for more information on this.\)
8+
9+
Often you’ll want more control over the formatting of your output than simply printing space-separated values. There are two ways to format your output; the first way is to do all the string handling yourself; using string slicing and concatenation operations you can create any layout you can imagine. The string type has some methods that perform useful operations for padding strings to a given column width; these will be discussed shortly. The second way is to use [formatted string literals](https://docs.python.org/3/reference/lexical_analysis.html#f-strings), or the [`str.format()`](https://docs.python.org/3/library/stdtypes.html#str.format) method.
10+
11+
The [`string`](https://docs.python.org/3/library/string.html#module-string) module contains a [`Template`](https://docs.python.org/3/library/string.html#string.Template) class which offers yet another way to substitute values into strings.
12+
13+
One question remains, of course: how do you convert values to strings? Luckily, Python has ways to convert any value to a string: pass it to the [`repr()`](https://docs.python.org/3/library/functions.html#repr) or [`str()`](https://docs.python.org/3/library/stdtypes.html#str) functions.
14+
15+
The [`str()`](https://docs.python.org/3/library/stdtypes.html#str) function is meant to return representations of values which are fairly human-readable, while [`repr()`](https://docs.python.org/3/library/functions.html#repr) is meant to generate representations which can be read by the interpreter \(or will force a [`SyntaxError`](https://docs.python.org/3/library/exceptions.html#SyntaxError) if there is no equivalent syntax\). For objects which don’t have a particular representation for human consumption, [`str()`](https://docs.python.org/3/library/stdtypes.html#str) will return the same value as [`repr()`](https://docs.python.org/3/library/functions.html#repr). 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.
16+
17+
Some examples:>>>
18+
19+
```text
20+
>>> s = 'Hello, world.'
21+
>>> str(s)
22+
'Hello, world.'
23+
>>> repr(s)
24+
"'Hello, world.'"
25+
>>> str(1/7)
26+
'0.14285714285714285'
27+
>>> x = 10 * 3.25
28+
>>> y = 200 * 200
29+
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
30+
>>> print(s)
31+
The value of x is 32.5, and y is 40000...
32+
>>> # The repr() of a string adds string quotes and backslashes:
33+
... hello = 'hello, world\n'
34+
>>> hellos = repr(hello)
35+
>>> print(hellos)
36+
'hello, world\n'
37+
>>> # The argument to repr() may be any Python object:
38+
... repr((x, y, ('spam', 'eggs')))
39+
"(32.5, 40000, ('spam', 'eggs'))"
40+
```
41+
42+
Here are two ways to write a table of squares and cubes:>>>
43+
44+
```text
45+
>>> for x in range(1, 11):
46+
... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
47+
... # Note use of 'end' on previous line
48+
... print(repr(x*x*x).rjust(4))
49+
...
50+
1 1 1
51+
2 4 8
52+
3 9 27
53+
4 16 64
54+
5 25 125
55+
6 36 216
56+
7 49 343
57+
8 64 512
58+
9 81 729
59+
10 100 1000
60+
61+
>>> for x in range(1, 11):
62+
... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
63+
...
64+
1 1 1
65+
2 4 8
66+
3 9 27
67+
4 16 64
68+
5 25 125
69+
6 36 216
70+
7 49 343
71+
8 64 512
72+
9 81 729
73+
10 100 1000
74+
```
75+
76+
\(Note that in the first example, one space between each column was added by the way [`print()`](https://docs.python.org/3/library/functions.html#print) works: by default it adds spaces between its arguments.\)
77+
78+
This example demonstrates the [`str.rjust()`](https://docs.python.org/3/library/stdtypes.html#str.rjust) method of string objects, which right-justifies a string in a field of a given width by padding it with spaces on the left. There are similar methods [`str.ljust()`](https://docs.python.org/3/library/stdtypes.html#str.ljust) and [`str.center()`](https://docs.python.org/3/library/stdtypes.html#str.center). 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 `x.ljust(n)[:n]`.\)
79+
80+
There is another method, [`str.zfill()`](https://docs.python.org/3/library/stdtypes.html#str.zfill), which pads a numeric string on the left with zeros. It understands about plus and minus signs:>>>
81+
82+
```text
83+
>>> '12'.zfill(5)
84+
'00012'
85+
>>> '-3.14'.zfill(7)
86+
'-003.14'
87+
>>> '3.14159265359'.zfill(5)
88+
'3.14159265359'
89+
```
90+
91+
Basic usage of the [`str.format()`](https://docs.python.org/3/library/stdtypes.html#str.format) method looks like this:>>>
92+
93+
```text
94+
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
95+
We are the knights who say "Ni!"
96+
```
97+
98+
The brackets and characters within them \(called format fields\) are replaced with the objects passed into the [`str.format()`](https://docs.python.org/3/library/stdtypes.html#str.format) method. A number in the brackets can be used to refer to the position of the object passed into the [`str.format()`](https://docs.python.org/3/library/stdtypes.html#str.format) method.>>>
99+
100+
```text
101+
>>> print('{0} and {1}'.format('spam', 'eggs'))
102+
spam and eggs
103+
>>> print('{1} and {0}'.format('spam', 'eggs'))
104+
eggs and spam
105+
```
106+
107+
If keyword arguments are used in the [`str.format()`](https://docs.python.org/3/library/stdtypes.html#str.format) method, their values are referred to by using the name of the argument.>>>
108+
109+
```text
110+
>>> print('This {food} is {adjective}.'.format(
111+
... food='spam', adjective='absolutely horrible'))
112+
This spam is absolutely horrible.
113+
```
114+
115+
Positional and keyword arguments can be arbitrarily combined:>>>
116+
117+
```text
118+
>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
119+
other='Georg'))
120+
The story of Bill, Manfred, and Georg.
121+
```
122+
123+
`'!a'` \(apply [`ascii()`](https://docs.python.org/3/library/functions.html#ascii)\), `'!s'` \(apply [`str()`](https://docs.python.org/3/library/stdtypes.html#str)\) and `'!r'` \(apply [`repr()`](https://docs.python.org/3/library/functions.html#repr)\) can be used to convert the value before it is formatted:>>>
124+
125+
```text
126+
>>> contents = 'eels'
127+
>>> print('My hovercraft is full of {}.'.format(contents))
128+
My hovercraft is full of eels.
129+
>>> print('My hovercraft is full of {!r}.'.format(contents))
130+
My hovercraft is full of 'eels'.
131+
```
132+
133+
An optional `':'` and format specifier can follow the field name. This allows greater control over how the value is formatted. The following example rounds Pi to three places after the decimal.>>>
134+
135+
```text
136+
>>> import math
137+
>>> print('The value of PI is approximately {0:.3f}.'.format(math.pi))
138+
The value of PI is approximately 3.142.
139+
```
140+
141+
Passing an integer after the `':'` will cause that field to be a minimum number of characters wide. This is useful for making tables pretty.>>>
142+
143+
```text
144+
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
145+
>>> for name, phone in table.items():
146+
... print('{0:10} ==> {1:10d}'.format(name, phone))
147+
...
148+
Jack ==> 4098
149+
Dcab ==> 7678
150+
Sjoerd ==> 4127
151+
```
152+
153+
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 `'[]'` to access the keys>>>
154+
155+
```text
156+
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
157+
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
158+
... 'Dcab: {0[Dcab]:d}'.format(table))
159+
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
160+
```
161+
162+
This could also be done by passing the table as keyword arguments with the ‘\*\*’ notation.>>>
163+
164+
```text
165+
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
166+
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
167+
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
168+
```
169+
170+
This is particularly useful in combination with the built-in function [`vars()`](https://docs.python.org/3/library/functions.html#vars), which returns a dictionary containing all local variables.
171+
172+
For a complete overview of string formatting with [`str.format()`](https://docs.python.org/3/library/stdtypes.html#str.format), see [Format String Syntax](https://docs.python.org/3/library/string.html#formatstrings).
173+
174+
#### 7.1.1. Old string formatting
175+
176+
The `%` operator can also be used for string formatting. It interprets the left argument much like a `sprintf()`-style format string to be applied to the right argument, and returns the string resulting from this formatting operation. For example:>>>
177+
178+
```text
179+
>>> import math
180+
>>> print('The value of PI is approximately %5.3f.' % math.pi)
181+
The value of PI is approximately 3.142.
182+
```
183+
184+
More information can be found in the [printf-style String Formatting](https://docs.python.org/3/library/stdtypes.html#old-string-formatting) section.
185+
186+
### 7.2. Reading and Writing Files
187+
188+
[`open()`](https://docs.python.org/3/library/functions.html#open) returns a [file object](https://docs.python.org/3/glossary.html#term-file-object), and is most commonly used with two arguments: `open(filename, mode)`.>>>
189+
190+
```text
191+
>>> f = open('workfile', 'w')
192+
```
193+
194+
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. _mode_ can be `'r'` when the file will only be read, `'w'`for only writing \(an existing file with the same name will be erased\), and `'a'` opens the file for appending; any data written to the file is automatically added to the end. `'r+'` opens the file for both reading and writing. The _mode_ argument is optional; `'r'` will be assumed if it’s omitted.
195+
196+
Normally, files are opened in _text mode_, 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 [`open()`](https://docs.python.org/3/library/functions.html#open)\). `'b'`appended to the mode opens the file in _binary mode_: 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.
197+
198+
In text mode, the default when reading is to convert platform-specific line endings \(`\n` on Unix, `\r\n` on Windows\) to just `\n`. When writing in text mode, the default is to convert occurrences of `\n` 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 `JPEG` or `EXE` files. Be very careful to use binary mode when reading and writing such files.
199+
200+
It is good practice to use the [`with`](https://docs.python.org/3/reference/compound_stmts.html#with) 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 [`with`](https://docs.python.org/3/reference/compound_stmts.html#with) is also much shorter than writing equivalent [`try`](https://docs.python.org/3/reference/compound_stmts.html#try)-[`finally`](https://docs.python.org/3/reference/compound_stmts.html#finally) blocks:>>>
201+
202+
```text
203+
>>> with open('workfile') as f:
204+
... read_data = f.read()
205+
>>> f.closed
206+
True
207+
```
208+
209+
If you’re not using the [`with`](https://docs.python.org/3/reference/compound_stmts.html#with) keyword, then you should call `f.close()` to close the file and immediately free up any system resources used by it. If you don’t explicitly close a file, Python’s garbage collector will eventually destroy the object and close the open file for you, but the file may stay open for a while. Another risk is that different Python implementations will do this clean-up at different times.
210+
211+
After a file object is closed, either by a [`with`](https://docs.python.org/3/reference/compound_stmts.html#with) statement or by calling `f.close()`, attempts to use the file object will automatically fail.>>>
212+
213+
```text
214+
>>> f.close()
215+
>>> f.read()
216+
Traceback (most recent call last):
217+
File "<stdin>", line 1, in <module>
218+
ValueError: I/O operation on closed file
219+
```
220+
221+
#### 7.2.1. Methods of File Objects
222+
223+
The rest of the examples in this section will assume that a file object called `f` has already been created.
224+
225+
To read a file’s contents, call `f.read(size)`, which reads some quantity of data and returns it as a string \(in text mode\) or bytes object \(in binary mode\). _size_ is an optional numeric argument. When _size_ 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 _size_ bytes are read and returned. If the end of the file has been reached, `f.read()` will return an empty string \(`''`\).&gt;&gt;&gt;
226+
227+
```text
228+
>>> f.read()
229+
'This is the entire file.\n'
230+
>>> f.read()
231+
''
232+
```
233+
234+
`f.readline()` reads a single line from the file; a newline character \(`\n`\) 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 `f.readline()` returns an empty string, the end of the file has been reached, while a blank line is represented by `'\n'`, a string containing only a single newline.&gt;&gt;&gt;
235+
236+
```text
237+
>>> f.readline()
238+
'This is the first line of the file.\n'
239+
>>> f.readline()
240+
'Second line of the file\n'
241+
>>> f.readline()
242+
''
243+
```
244+
245+
For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code:&gt;&gt;&gt;
246+
247+
```text
248+
>>> for line in f:
249+
... print(line, end='')
250+
...
251+
This is the first line of the file.
252+
Second line of the file
253+
```
254+
255+
If you want to read all the lines of a file in a list you can also use `list(f)` or `f.readlines()`.
256+
257+
`f.write(string)` writes the contents of _string_ to the file, returning the number of characters written.&gt;&gt;&gt;
258+
259+
```text
260+
>>> f.write('This is a test\n')
261+
15
262+
```
263+
264+
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:&gt;&gt;&gt;
265+
266+
```text
267+
>>> value = ('the answer', 42)
268+
>>> s = str(value) # convert the tuple to string
269+
>>> f.write(s)
270+
18
271+
```
272+
273+
`f.tell()` 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.
274+
275+
To change the file object’s position, use `f.seek(offset, from_what)`. The position is computed from adding _offset_ to a reference point; the reference point is selected by the _from\_what_ argument. A _from\_what_ 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. _from\_what_ can be omitted and defaults to 0, using the beginning of the file as the reference point.&gt;&gt;&gt;
276+
277+
```text
278+
>>> f = open('workfile', 'rb+')
279+
>>> f.write(b'0123456789abcdef')
280+
16
281+
>>> f.seek(5) # Go to the 6th byte in the file
282+
5
283+
>>> f.read(1)
284+
b'5'
285+
>>> f.seek(-3, 2) # Go to the 3rd byte before the end
286+
13
287+
>>> f.read(1)
288+
b'd'
289+
```
290+
291+
In text files \(those opened without a `b` 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 `seek(0, 2)`\) and the only valid _offset_ values are those returned from the `f.tell()`, or zero. Any other _offset_ value produces undefined behaviour.
292+
293+
File objects have some additional methods, such as `isatty()` and `truncate()` which are less frequently used; consult the Library Reference for a complete guide to file objects.
294+
295+
#### 7.2.2. Saving structured data with [`json`](https://docs.python.org/3/library/json.html#module-json)
296+
297+
Strings can easily be written to and read from a file. Numbers take a bit more effort, since the `read()` method only returns strings, which will have to be passed to a function like [`int()`](https://docs.python.org/3/library/functions.html#int), which takes a string like `'123'` 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.
298+
299+
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 [JSON \(JavaScript Object Notation\)](http://json.org/). The standard module called [`json`](https://docs.python.org/3/library/json.html#module-json) can take Python data hierarchies, and convert them to string representations; this process is called _serializing_. Reconstructing the data from the string representation is called _deserializing_. 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.
300+
301+
Note
302+
303+
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.
304+
305+
If you have an object `x`, you can view its JSON string representation with a simple line of code:&gt;&gt;&gt;
306+
307+
```text
308+
>>> import json
309+
>>> json.dumps([1, 'simple', 'list'])
310+
'[1, "simple", "list"]'
311+
```
312+
313+
Another variant of the [`dumps()`](https://docs.python.org/3/library/json.html#json.dumps) function, called [`dump()`](https://docs.python.org/3/library/json.html#json.dump), simply serializes the object to a [text file](https://docs.python.org/3/glossary.html#term-text-file). So if `f` is a [text file](https://docs.python.org/3/glossary.html#term-text-file) object opened for writing, we can do this:
314+
315+
```text
316+
json.dump(x, f)
317+
```
318+
319+
To decode the object again, if `f` is a [text file](https://docs.python.org/3/glossary.html#term-text-file) object which has been opened for reading:
320+
321+
```text
322+
x = json.load(f)
323+
```
324+
325+
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 [`json`](https://docs.python.org/3/library/json.html#module-json) module contains an explanation of this.
326+
327+
See also
328+
329+
[`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle) - the pickle module
330+
331+
Contrary to [JSON](https://docs.python.org/3/tutorial/inputoutput.html#tut-json), _pickle_ 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.
332+

SUMMARY.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22

33
* [Introduction](README.md)
44
* [0. The Python Tutorial](first-chapter.md)
5-
* [9. Classes](9.-classes.md)
6-
* [8. Errors and Exceptions](8.-errors-and-exceptions.md)
75
* [1. Whetting Your Appetite](1.-whetting-your-appetite.md)
86
* [2. Using the Python Interpreter](2.-using-the-python-interpreter.md)
7+
* [7. Input and Output](7.-input-and-output.md)
8+
* [8. Errors and Exceptions](8.-errors-and-exceptions.md)
9+
* [9. Classes](9.-classes.md)
910

0 commit comments

Comments
 (0)