Python3 Input and Output
In the previous chapters we have already touched on Python's input and output capabilities. This chapter describes Python input and output in detail.
Pretty output formatting
Python has two ways to output values: expression statements and the print() function.
A third way is to use the write() method of a file object; the standard output file can be referenced with sys.stdout.
If you want more varied output forms, you can use the str.format() function to format output values.
If you want to convert output values to strings, you can use the repr() or str() function.
- str(): function returns a user-readable representation.
- repr(): produces an interpreter-readable representation.
For example
s
=
'Hello, Runoob'
str
(
s
)
'Hello, Runoob'
repr
(
s
)
"'Hello, Runoob'"
str
(
1
/
7
)
'0.14285714285714285'
x
=
10
3.25
y
=
200
200
s
=
'the value of x is: '
repr
(
x
)
', the value of y is:'
repr
(
y
)
'...'
(
s
)
The value of x is:
32.5
,
the value of y is:
40000
...
The repr() function can escape special characters in a string
...
hello
=
'hello, runoob\n'
hellos
=
repr
(
hello
)
(
hellos
)
'hello, runoob\n'
The argument of repr() can be any Python object
...
repr
(
(
x
,
y
,
(
'Google'
,
'Runoob'
)
)
)
"(32.5, 40000, ('Google', 'Runoob'))"
Here are two ways to output a table of squares and cubes:
for
x
in
range
(
1
,
11
)
:
...
(
repr
(
x
)
.
rjust
(
2
)
,
repr
(
x*x
)
.
rjust
(
3
)
,
end
=
' '
)
...
Note the use of 'end' in the previous line
...
(
repr
(
xxx
)
.
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
for
x
in
range
(
1
,
11
)
:
...
(
'{0:2d} {1:3d} {2:4d}'
.
format
(
x
,
x*x
,
xxx
)
)
...
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
**Note:** In the first example, the spaces between columns are added by print().
This example demonstrates the rjust() method of string objects, which right-aligns a string and pads it with spaces on the left.
There are similar methods such as ljust() and center(). These methods do not write anything; they merely return a new string.
Another method, zfill(), pads a number with zeros on the left, as shown below:
'12'
.
zfill
(
5
)
'00012'
'-3.14'
.
zfill
(
7
)
'-003.14'
'3.14159265359'
.
zfill
(
5
)
'3.14159265359'
The basic use of str.format() is as follows:
(
'{} website: "{}!"'
.
format
(
'Runoob Tutorial'
,
'www.runoob.com'
)
)
Runoob Tutorial URL:
"www.runoob.com!"
The braces and the characters inside them (called format fields) are replaced by the arguments to format().
A number in the braces refers to the position of the passed object in format(), as shown below:
(
'{0} and {1}'
.
format
(
'Google'
,
'Runoob'
)
)
Google and Runoob
(
'{1} and {0}'
.
format
(
'Google'
,
'Runoob'
)
)
Runoob and Google
If keyword arguments are used in format(), their values are referenced by using that name.
(
'{name} website: {site}'
.
format
(
name
=
'Runoob Tutorial'
,
site
=
'www.runoob.com'
)
)
Runoob Tutorial website: www.
runoob
.
com
Positional and keyword arguments can be combined freely:
(
'Site list {0}, {1}, and {other}.'
.
format
(
'Google'
,
'Runoob'
,
other
=
'Taobao'
)
)
Site list Google
,
Runoob
,
and Taobao.
!a (using ascii()), !s (using str()) and !r (using ** repr()**) can be used to convert a value before formatting it:
import
math
(
'The value of the constant PI is approximately: {}.'
.
format
(
math
.
pi
)
)
The value of the constant PI is approximately:
3.141592653589793
。
(
'The value of the constant PI is approximately: {!r}.'
.
format
(
math
.
pi
)
)
The value of the constant PI is approximately:
3.141592653589793
。
The optional : and format specifier can follow the field name. This allows better formatting of values. The following example keeps Pi to three decimal places:
import
math
(
'The value of the constant PI is approximately {0:.3f}.'
.
format
(
math
.
pi
)
)
The value of the constant PI is approximately
3.142
。
Passing an integer after : guarantees that the field has at least that much width. This is useful for beautifying tables.
table
=
{
'Google'
:
1
,
'Runoob'
:
2
,
'Taobao'
:
3
}
for
name
,
number
in
table.
items
(
)
:
...
(
'{0:10} ==> {1:10d}'
.
format
(
name
,
number
)
)
...
==>
1
Runoob
==>
2
Taobao
==>
3
If you have a very long format string and do not want to split it up, it is a good idea to format by variable name rather than by position.
The simplest is to pass a dictionary and use square brackets [] to access the values:
table
=
{
'Google'
:
1
,
'Runoob'
:
2
,
'Taobao'
:
3
}
(
'Runoob: {0[Runoob]:d}; Google: {0[Google]:d}; Taobao: {0[Taobao]:d}'
.
format
(
table
)
)
Runoob:
2
;
Google:
1
;
Taobao:
3
The same can be achieved by using ** before the table variable:
table
=
{
'Google'
:
1
,
'Runoob'
:
2
,
'Taobao'
:
3
}
(
'Runoob: {Runoob:d}; Google: {Google:d}; Taobao: {Taobao:d}'
.
format
(
**table
)
)
Runoob:
2
;
Google:
1
;
Taobao:
3
Old-style string formatting
The % operator can also perform string formatting. It treats the left argument as a sprintf() -style format string, substitutes the right-hand values and returns the formatted string. For example:
import
math
(
'The value of the constant PI is approximately: %5.3f.'
%
math
.
pi
)
The value of the constant PI is approximately:
3.142
。
Because str.format() is relatively new, most Python code still uses the % operator. But since this old-style formatting will eventually be removed from the language, str.format() should be used more.
Reading keyboard input
Python provides the The built-in input() functionReads one line of text from standard input; by default the standard input is the keyboard.
Example
#!/usr/bin/python3
str
=
input
(
"Please enter: "
)
;
(
"What you entered is: "
,
str
)
This produces the following result corresponding to the input:
请输入:Runoob Tutorial
你输入的内容是: Runoob Tutorial
Reading and writing files
In Python, file operations are performed through the open() function. It returns a file object used for subsequent read or write operations.
open() The basic syntax is as follows:
open(filename, mode)
- **filename:** the path of the file to access (a string).
- **mode:** the file opening mode, specifying how the file is read or written (read-only, write, append, etc.). This parameter is optional and defaults to
r(read-only).
Common file opening modes are as follows (focus on r / w / a):
| Mode | Description |
|---|---|
| r | Open the file read-only (the default mode); the file must exist and the file pointer is at the beginning. |
| rb | Open the file read-only in binary format (e.g. for images or videos); the file pointer is at the beginning. |
| r+ | Open the file for both reading and writing; the file must exist and the pointer is at the beginning. |
| rb+ | Open the file for binary reading and writing; the pointer is at the beginning. |
| w | Open the file write-only. If the file exists it will beclear; if it does not exist, a new file is created. |
| wb | Open the file write-only in binary format. If the file exists it is truncated; if not, a new file is created. |
| w+ | Open the file for reading and writing. If the file exists it is truncated; if not, a new file is created. |
| wb+ | Open the file for binary reading and writing. If the file exists it is truncated; if not, a new file is created. |
| a | Open the file in append mode. If the file exists, written content is appended to the end; if not, a new file is created. |
| ab | Open the file for binary append writing; content is appended to the end; if it does not exist, a new file is created. |
| a+ | Open the file for reading and writing, with the pointer at the end by default (append mode); if it does not exist, a new file is created. |
| ab+ | Open the file for binary reading and writing, with the pointer at the end by default; if it does not exist, a new file is created. |
**Note:** Adding b after the mode means working with files in binary form, often used for non-text files such as images and audio.
The following figure summarizes these modes well:
| Mode | r | r+ | w | w+ | a | a+ |
|---|---|---|---|---|---|---|
| Read | + | + | + | + | ||
| Write | + | + | + | + | + | |
| creation | + | + | + | + | ||
| Overwrite | + | + | ||||
| Pointer at the beginning | + | + | + | + | ||
| Pointer at the end | + | + |
The following example writes a string into the file foo.txt:
Example
#!/usr/bin/python3
Open a file
f
=
open
(
"/tmp/foo.txt"
,
"w"
)
f.
write
(
"Python is a very good language.\nYes, it really is very good!!\n"
)
Close the opened file
f.
close
(
)
- The first argument is the name of the file to open.
- The second argument is a string describing how the file is used. mode can be 'r' for read-only, 'w' for writing only (an existing file with the same name will be deleted), and 'a' to append to the file; any data written is automatically added to the end. 'r+' is used for both reading and writing. The mode argument is optional; 'r' is the default.
Now open the file foo.txt; it displays the following:
$ cat /tmp/foo.txt
Python 是一个非常好的语言。
是的,的确非常好!!
Methods of file objects
The remaining examples in this section assume that a file object called f has already been created.
f.read()
To read the contents of a file, call f.read(size), which reads a certain amount of data and returns it as a string or bytes object.
size is an optional numeric argument. When size is omitted or negative, the entire contents of the file are read and returned.
The following example assumes that the file foo.txt already exists (it was created in the example above):
Example
#!/usr/bin/python3
Open a file
f
=
open
(
"/tmp/foo.txt"
,
"r"
)
str
=
f.
read
(
)
(
str
)
Close the opened file
f.
close
(
)
Running the above program, the output is:
Python 是一个非常好的语言。
是的,的确非常好!!
f.readline()
f.readline() reads a single line from the file. The newline character is '\n'. If f.readline() returns an empty string, the last line has already been read.
Example
#!/usr/bin/python3
Open a file
f
=
open
(
"/tmp/foo.txt"
,
"r"
)
str
=
f.
readline
(
)
(
str
)
Close the opened file
f.
close
(
)
Running the above program, the output is:
Python 是一个非常好的语言。
f.readlines()
f.readlines() returns all the lines contained in the file.
If the optional parameter sizehint is set, that many bytes are read and split into lines.
Example
#!/usr/bin/python3
Open a file
f
=
open
(
"/tmp/foo.txt"
,
"r"
)
str
=
f.
readlines
(
)
(
str
)
Close the opened file
f.
close
(
)
Running the above program, the output is:
['Python 是一个非常好的语言。\n', '是的,的确非常好!!\n']
Another way is to iterate over a file object and read each line:
Example
#!/usr/bin/python3
Open a file
f
=
open
(
"/tmp/foo.txt"
,
"r"
)
for
line
in
f:
(
line
,
end
=
''
)
Close the opened file
f.
close
(
)
Running the above program, the output is:
Python 是一个非常好的语言。
是的,的确非常好!!
This method is simple but does not offer good control. Because the two mechanisms differ, it is best not to mix them.
f.write()
f.write(string) writes string into the file and returns the number of characters written.
Example
#!/usr/bin/python3
Open a file
f
=
open
(
"/tmp/foo.txt"
,
"w"
)
num
=
f.
write
(
"Python is a very good language.\nYes, it really is very good!!\n"
)
(
num
)
Close the opened file
f.
close
(
)
Running the above program, the output is:
29
To write something that is not a string, it must first be converted:
Example
#!/usr/bin/python3
Open a file
f
=
open
(
"/tmp/foo1.txt"
,
"w"
)
value
=
(
'www.runoob.com'
,
14
)
s
=
str
(
value
)
f.
write
(
s
)
Close the opened file
f.
close
(
)
After running the above program, open the foo1.txt file:
$ cat /tmp/foo1.txt
('www.runoob.com', 14)
f.tell()
f.tell() returns the current read/write position of the file (the position of the file pointer). The file pointer is the byte offset from the beginning of the file. f.tell() returns an integer representing the current position of the file pointer.
f.seek()
To change the current position of the file pointer, use the f.seek(offset, from_what) function.
f.seek(offset, whence) moves the file pointer to a specified position.
offset is the displacement relative to the whence parameter; a from_what value of 0 means the beginning, 1 means the current position and 2 means the end of the file, for example:
- seek(x,0) : move x characters from the starting position, i.e. the first character of the first line of the file
- seek(x,1) : move x characters forward from the current position
- seek(-x,2) : move x characters backward from the end of the file
The from_what value defaults to 0, i.e. the beginning of the file. Here is a complete example:
f
=
open
(
'/tmp/foo.txt'
,
'rb+'
)
f.
write
(
b
'0123456789abcdef'
)
16
f.
seek
(
5
)
Move to the sixth byte of the file
5
f.
read
(
1
)
b
'5'
f.
seek
(
3
,
2
)
Move to the third-to-last byte of the file
13
f.
read
(
1
)
b
'd'
f.close()
In text files (those opened in a mode without b), positioning is only possible relative to the beginning of the file.
When you are done with a file, call f.close() to close it and free system resources; trying to use the file again raises an exception.
f.
close
(
)
f.
read
(
)
Traceback
(
most recent call last
)
:
File
"
,
line
1
,
in
?
ValueError
: I/O operation on closed
file
When working with a file object, using the with keyword is a very good approach. It closes the file properly for you when done, and is shorter to write than a try - finally block:
with
open
(
'/tmp/foo.txt'
,
'r'
)
as
f:
...
read_data
=
f.
read
(
)
f.
closed
True
File objects have other methods such as isatty() and truncate(), but these are usually used less often.
The pickle module
Python's pickle module implements basic data serialization and deserialization.
With the serialization operations of the pickle module we can save information about objects running in a program to a file for permanent storage.
With the deserialization operations of the pickle module, we can recreate from a file the objects saved by the previous run of the program.
Basic interface:
pickle.dump(obj, file, [,protocol])
With the pickle object, file can be opened for reading:
x = pickle.load(file)
**Note:** Read a string from file and reconstruct it into the original Python object.
file: A file-like object with read() and readline() interfaces.
Example 1
#!/usr/bin/python3
import
pickle
Use the pickle module to save a data object to a file
data1
=
{
'a'
:
[
1
,
2.0
,
3
,
4
+6j
]
,
'b'
:
(
'string'
,
u
'Unicode string'
)
,
'c'
:
None
}
selfref_list
=
[
1
,
2
,
3
]
selfref_list.
append
(
selfref_list
)
output
=
open
(
'data.pkl'
,
'wb'
)
Pickle dictionary using protocol 0.
pickle
.
dump
(
data1
,
output
)
Pickle the list using the highest protocol available.
pickle
.
dump
(
selfref_list
,
output
,
1
)
output.
close
(
)
Example 2
#!/usr/bin/python3
import
pprint
,
pickle
# Use the pickle module to rebuild a Python object from a file
pkl_file
=
open
(
'data.pkl'
,
'rb'
)
data1
=
pickle
.
load
(
pkl_file
)
pprint
.
pprint
(
data1
)
data2
=
pickle
.
load
(
pkl_file
)
pprint
.
pprint
(
data2
)
pkl_file.
close
(
)