SoFunction
Updated on 2025-03-04

Introduction to Python Page 7/10


Chapter 7 Input and Output
There are several ways to output from the program; the data can be displayed in readable form or saved to a file for future use. This chapter discusses some input and output methods.

7.1 Output format control
So far we have seen two ways to output values: expression statements and print statements. (The third method is to use the write() method of the file object, and the standard output file can be referenced. See the library reference manual).

We often need to control the output format, not just display space-separated values. There are two ways to control the output format: one is to process the string yourself, and use string fragments and merge operations to produce any imaginable format. The standard module string contains useful operations such as filling a string to a specified column width, as will be mentioned later.

Another way is to use the % operator, which takes a string as the left operator. It converts the right operator into a string according to the format of C's sprintf() function and returns the conversion result.

The question is: How to convert the value to a string?

Fortunately, Python has a way to convert any value into a string: use the repr() function, or write the value between two back quotes (``). For example:

>>> x = 10 * 3.14
>>> y = 200*200
>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
>>> print s
The value of x is 31.4, and y is 40000...
>>> # Reverse quotes are also suitable for non-numeric types
... p = [x, y]
>>> ps = repr(p)
>>> ps
'[31.4, 40000]'
>>> # Convert strings to string quotes and backslashes to strings
... hello = 'hello, world\n'
>>> hellos = `hello`
>>> print hellos
'hello, world\012'
>>> # There can be a sequence table in the back quotes
... `x, y, ('spam', 'eggs')`
"(31.4, 40000, ('spam', 'eggs'))"


Here are two ways to write square and cubic tables:

>>> import string
>>> for x in range(1, 11):
...     print (`x`, 2), (`x*x`, 3),
...     # The comma at the end of the previous line means no line wrapping
...     print (`x*x*x`, 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):
...     print'%2d %3d %4d' % (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


Note that there is an additional space between the items output in the print, which is the rule of print.

This example shows the usage of function(), which can put a string in the specified width and right-align it with spaces on the left. Similar functions include () and (). These functions do not output outwards, but return the converted string. If the input string is too long, it will not be truncated but will be returned as is. Such processing may invalidate your column alignment, but this may be a little better than truncation, the result of truncation is that we see an incorrect value. (If you really need truncation, you can always add another layer of fragments, such as (x,n)[0:n]).

There is also a function (), which can fill in zeros on the left side of the numeric value. This function can handle cases with addition and minus signs:

>>> ('12', 5)
'00012'
>>> ('-3.14', 7)
'-003.14'
>>> ('3.14159265359', 5)
'3.14159265359'


The usage of the % operator is as follows:

>>> import math
>>> print 'The value of PI is approximately %5.3f.' % 
The value of PI is approximately 3.142.


If there are multiple values, it can be given in a sequence table, then there must be multiple formats in the format string, such as:

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> for name, phone in ():
...     print'%-10s ==> %10d' % (name, phone)
... 
Jack       ==>       4098
Dcab       ==>    8637678
Sjoerd     ==>       4127


Most formats are used the same as C and require that the type of value to be output meets the format requirements. However, if you do not throw an exception error, the kernel heap column will not be generated. Python's %s format is much wider: if the corresponding output item is not a string object, use the built-in function of str() to turn it into a string. In the format specification, the width specified is *, which indicates that there is an additional integer of the specified width in the following output item. C format %n and %p are not supported.

If you have a long format string that doesn't want to separate it, you can specify the name in the specified format, so you don't need to correspond to the format and name in order. This format is "%(variable name) format", for example:

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
Jack: 4098; Sjoerd: 4127; Dcab: 8637678


The output item here is always a dictionary. The values ​​of the dictionary are the values ​​to be output, and the key values ​​of the dictionary are the names of each value. This output format is often used in conjunction with the built-in function var(), which returns a dictionary containing all local variables.

7.2 Read and write files
Open() opens a file object and often uses two parameters: "open(file name, pattern)". For example:

>>> f=open('/tmp/workfile', 'w')
>>> print f
<open file '/tmp/workfile', mode 'w' at 80a0960>


The first argument is a string containing the file name, and the second argument is a string in the file opening mode. Mode ‘r ’ means reading, ‘w’ means writing only (the existing file with the same name is cleared), ‘a’ means adding the open file at the end, and ‘r+’ means opening the file can be read or written. The parameter on the open mode is optional, the default is 'r' mode.

Adding ‘b’ to the mode in Windows and Macintosh means opening the file in binary format, such as ‘rb’, ‘wb ’, ‘r+b’. Windows handles text files and binary files differently, and the newline characters in text files change when reading and writing. This behind-the-scenes modification to file data does not affect ASCII text files, but will destroy binary data such as JPEG or ".EXE" files. You must use binary format to read and write such files. (The exact description of text patterns in Macintosh depends on the C library used).

7.2.1 Methods of file objects
The examples later in this section assume that a file object named f has been created.

In order to read the file content, a certain number of bytes can be read into the data returned as a string. size is an optional numerical parameter. When size or size is omitted, read the entire file and return it as a string; if the file is twice as large as your machine's memory, that is your problem. When the positive size is specified, read in and return the size bytes. If the end of the file is read, () returns an empty string (""). like:

 
>>> ()
'This is the entire file.\012'
>>> ()
''
 


() Read a line from the file, and the returned string will include an ending newline character (\n). If there is no line character on the last line of the file, the string read from the line will also have no ending newline character. In this way, the result returned by readline() will not be ambiguous. When the result is read into an empty string, it must be at the end of the file. When the '\n' is read into an empty line.

>>> ()
'This is the first line of the file.\012'
>>> ()
'Second line of the file\012'
>>> ()
''


() Repeatedly call () to return a list containing all lines of the file.

>>> ()
['This is the first line of the file.\012', 'Second line of the file\012']


(string) Write the contents of the string into the file and return None.
 
>>> ('This is a test\n')
 


() Returns the current read and write of the file object, and calculates it according to the number of bytes starting from the file. To change the read and write position, use "(displacement, where from)". The read and write position is calculated based on a reference point plus displacement. The reference point is specified with the "From there" parameter. When 0 is taken, it starts from the file header, when 1 is taken, it is calculated based on the current position, and when 2 is taken, it is calculated from the file end. The default value is 0, and it starts with the file.

>>> f=open('/tmp/workfile', 'r+')
>>> ('0123456789abcdef')
>>> (5)     # Follow 5 bytes from the file header to reach the 6th character
>>> (1)        
'5'
>>> (-3, 2) # Go to the first 3 characters at the end
>>> (1)
'd'


After using an external file, call () to close the file, and release the system resources occupied by opening the file. If the file object is closed, it will be invalid.

>>> ()
>>> ()
Traceback (innermost last):
  File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file


There are other less commonly used methods for file objects, such as isatty() and truncate(), see the library reference manual.

7.2.2 pickle module
Strings can be read easily from or written to files. Reading numeric values ​​is a bit troublesome, because the read() method always returns a string, and passes the read string to a function like() and converts a string like '123' into the corresponding integer value 123. However, when you want to save more complex data types such as lists, dictionaries, or class instances, reading and writing are much more complex.

Python is designed to allow programmers to write code that debugs and saves complex data types without having to repeatedly write code that saves complex data types. It provides a standard module called pickle. This amazing module can convert almost any Python object into a string representation. This process is called pickling, and restoring an object from a string representation of an object is called recovery. Between pickling and back pickling, the string representation of the object can be saved in a file or data, or even transferred to a remote computer over a network connection.

If you have an object x and a writable file object f, the easiest way to pickle the object is the following line of code:

(x, f)

In order to restore the object, if the file just now has been opened for reading and the file object name is still f, then:

x = (f)

(There are other uses for pickling and recovery. You can pickle multiple objects and do not write data to the file. Please refer to the library reference manual for details).

pickle is a standard way to save Python objects and be called when they are later run by other programs or the same program. The term for this practice is called "persistent objects". Because pickle is widely used, many Python extension authors are paying attention to making newly added data types such as matrices properly pickled and restored.
Previous page12345678910Next pageRead the full text