Output format beautification
Python two ways to output values: Expression statements and print () functions. (The third way is to use the write () method of the file object; The standard output file can be referenced with sys.stdout.) )
If you want the output to be more diverse, you can use the Str.format () function to format the output value.
If you want to convert the output value to a string, you can do so using the repr () or str () function.
The STR () function returns a user-readable representation.
Repr () produces an interpreter-readable representation.
For example
>>> s = ' Hello, world ' >>> Str (s) ' Hello, World ' >>> repr (s) "' Hello, world. '" >>> str (1/7) ' 0.14285714285714285 ' >>> x = ten * 3.25>>> y = $ * 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 () function can escape special characters in a string ... hello = ' Hello, world\n ' >>> hellos = repr (hello) >>> print (hellos The parameters of ' Hello, world\n ' >>> # repr () can be any object of Python ... repr ((x, y, (' spam ', ' eggs ')) "(32.5, 40000, (' spam ', ' eggs ') ))"
Here are two ways to output a square-cubic table:
>>> for x in range (1, one): ... . Print (repr (x). Rjust (2), repr (x*x). Rjust (3), end= ') ... # Note the use of the previous line ' end ' ... Print (Repr (x*x*x). Rjust (4)) ... 1 1 1 2 4 8 3 9 4 5 216 6 7 8 9 72910 1000>>> for x in range (1, one): .... Print (' {0:2d} {1:3d} {2:4d} '. Format (x, X*x, x*x*x) ... 1 1 1 2 4 8 3 9 4 5 216 6 7 343 8 9 bayi 72910 100 1000
Note: in the first example, the space between each column is added by print ().
This example shows the Rjust () method of the String object, which can put a string on the right and fill the left padding with spaces.
There are similar methods, such as Ljust () and center (). These methods do not write anything, they simply return a new string.
Another method, Zfill (), fills 0 on the left side of the number, as follows:
>>> ' Zfill (5) ' 00012 ' >>> ' -3.14 '. Zfill (7) ' -003.14 ' >>> ' 3.14159265359 '. Zfill (5) ' 3.14159265359 '
The basic use of Str.format () is as follows:
>>> print (' We're the {} who say ' {}! '. Format (' Knights ', ' Ni ')) We are the Knights say "ni!"
The parentheses and the characters inside them (called formatted fields) are replaced by the parameters in format ().
The number in parentheses is used to point to the location of the incoming object in format (), as follows:
>>> print (' {0} and {1} '. Format (' spam ', ' eggs ')) spam and eggs>>> print (' {1} and {0} '. Format (' spam ', ' Eggs ')) eggs and spam
If keyword parameters are used in format (), their values point to parameters that use that name.
>>> print (' This {food} is {adjective}. '. Format ( ..... food= ' spam ', adjective= ' absolutely horrible ') this spam is absolutely horrible.
The position and keyword parameters can be arbitrarily combined:
>>> print (' The story of {0}, {1}, and {other} '. Format (' Bill ', ' Manfred ', other= ' Georg ')) The story of Bill, Manfred, and Georg.
'!a ' (using ASCII ()), '!s ' (using str ()) and '!r ' (using repr ()) can be used to convert a value before it is formatted:
>>> Import math>>> Print (' The value of PI is approximately {}. '). Format (MATH.PI)) The value of pi is approximately 3.14159265359.>>> print (' The value of pi is approximately {!r}. ' . Format (Math.PI)) The value of pi is approximately 3.141592653589793.
The option ': ' and the format identifier can be followed by the field name. This allows for better formatting of values. The following example holds the Pi to three digits after the decimal point:
>>> Import math>>> Print (' The value of PI is approximately {0:.3f} '. Format (MATH.PI)) The value of pi is approximately 3.142.
Passing in an integer after ': ' Guarantees that the field has at least as many widths. Useful for beautifying tables.
>>> table = {' Sjoerd ': 4127, ' Jack ': 4098, ' dcab ': 7678}>>> for Name, phone in Table.items (): ... Print (' {0:10} ==> {1:10d} '. Format (name, phone) ... Jack ==> 4098Dcab ==> 7678Sjoerd ==> 4127
If you have a long format string and you don't want to separate it, it would be nice to pass the variable name instead of the location when you format it.
The simplest is to pass in a dictionary and then use square brackets ' [] ' to access the key value:
>>> 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
You can also achieve the same functionality by using ' * * ' before the table variable:
>>> 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
Legacy string Formatting
The% operator can also implement string formatting. It takes the left argument as a formatted string similar to the sprintf () format, substituting the right side and returning the formatted string. For example:
>>> Import math>>> Print (' The value of pi is approximately%5.3f. '% Math.PI) The value of pi is Approxim Ately 3.142.
Because Str.format () compares new functions, most Python code still uses the% operator. However, since this legacy format will eventually be removed from the language, more Str.format () should be used.
Read and write files
Open () Returns a file object with the following basic syntax format:
Open (filename, mode)
Instance:
>>> f = open ('/tmp/workfile ', ' W ')
- The first parameter is the name of the file to open.
- The second parameter describes how the file uses the characters. Mode can be ' r ' if the file is read only, ' W ' is only used for writing (if there is a file with the same name will be deleted), and ' A ' is used to append the file contents; Any data that is written will be automatically added to the end. ' r+ ' is also used for both reading and writing. The mode parameter is optional; ' R ' will be the default value.
Methods for File objects
The rest of the examples in this section assume that a file object called F has been created.
F.read ()
To read the contents of a file, call F.read (size), which reads a certain number of data and then returns as a string or byte object.
Size is an optional parameter of the numeric type. When size is ignored or negative, all the contents of the file are read and returned.
>>> f.read () ' This is the entire file.\n ' >>> f.read () '
F.readline ()
F.readline () reads a separate line from the file. The line break is ' \ n '. F.readline () If an empty string is returned, the last line has already been read.
>>> f.readline () ' This was the first line of the file.\n ' >>> f.readline () ' Second line of the file\n ' >&G T;> F.readline () "
F.readlines ()
F.readlines () returns all the rows contained in the file.
If you set the optional parameter Sizehint, the bytes of the specified length are read, and the bytes are split by row.
>>> f.readlines () [' This was the first line of the file.\n ', ' Second line of the ' file\n ']
Another way is to iterate over a file object and then read each line:
>>> for line in F: ... Print (line, end= ") ... This is the first line of the file. Second Line of the file
This method is simple, but does not provide a good control. Because the processing mechanism of the two is different, it is best not to mix.
F.write ()
F.write (String) writes a string to the file, and then returns the number of characters written.
>>> F.write (' This is a test\n ') 15
If you are writing something that is not a string, you will need to convert it first:
>>> value = (' The answer ', $) >>> s = str (value) >>> F.write (s) 18
F.tell ()
F.tell () returns the current location of the file object, which is the number of bytes that are counted from the beginning of the file.
F.seek ()
If you want to change the current location of the file, you can use the F.seek (offset, from_what) function.
The value of From_what, if 0 indicates the beginning, if 1 represents the current position, and 2 indicates the end of the file, for example:
- Seek (x,0): Moves x characters from the start position, which is the beginning of the first line character of the file
- Seek (x,1): Indicates that x characters are moved backwards from the current position
- Seek (-x,2): Represents moving the X-character forward from the end of a file
The From_what value defaults to 0, which is the beginning of the file. A complete example is given below:
>>> f = open ('/tmp/workfile ', ' rb+ ') >>> f.write (b ' 0123456789abcdef ') 16>>> F.seek (5) # Move to the sixth byte of a file 5>>> F.read (1) B ' 5 ' >>> f.seek (-3, 2) # move to the last third byte of the file 13>>> F.read (1) B ' d '
F.close ()
In text files (those that do not have B in the Open file mode), they are only positioned relative to the starting position of the file.
When you have finished processing a file, call F.close () to close the file and release the system's resources, and throw an exception if you try to call the file again.
>>> f.close () >>> f.read () Traceback (most recent call last): File ' <stdin> ', line 1, in? VALUEERROR:I/O operation on closed file<pre><p> when working with a file object, using the WITH keyword is a great way to do it. At the end, it will help you close the file correctly. It is also written to be shorter than the try-finally statement block:</p><pre>>>> with open ('/tmp/workfile ', ' R ') as F: ... Read_data = F.read () >>> f.closedtrue
File objects also have other methods, such as Isatty () and trucate (), but these are usually less used.
Pickle Module
Python's pickle module implements basic data sequence and deserialization.
Through the serialization of the Pickle module we are able to save the object information that is running in the program to the file and store it permanently.
With the deserialization of the Pickle module, we were able to create the last object saved by the program from the file.
Basic interface:
Pickle.dump (obj, file, [, Protocol])
With the Pickle object, you can open the file as read:
x = pickle.load (file)
Note: reads a string from file and reconstructs it as the original Python object.
File : class Files object with Read () and ReadLine () interfaces.
Example 1:
#使用pickle模块将数据对象保存到文件import pickledata1 = {' 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 Protoco L 0.pickle.dump (data1, Output) # Pickle the list using the highest protocol available.pickle.dump (selfref_list, output,-1) Output.close ()
Example 2:
#使用pickle模块从文件中重构python对象import pprint, picklepkl_file = open (' data.pkl ', ' RB ') data1 = Pickle.load (pkl_file) Pprint.pprint (data1) data2 = Pickle.load (pkl_file) pprint.pprint (data2) pkl_file.close ()
Python3 Input and output