[Python] Python input and output, python Input and Output

Source: Internet
Author: User

[Python] Python input and output, python Input and Output
Beautify the output format

Python provides two output methods:Expression statement and print () function(The third method is to use the write () method of the file object. The standard output file can be referenced by sys. stdout)

You can useStr. format () functionTo format the output value.

If you want to convert the output value to a string, you can use the repr () or str () function.
The str () function returns an easy-to-read expression.
Repr () generates an easy-to-read expression for the interpreter.

For example

s = 'Hello,world.'str(s)>>>'Hello,world.'repr(s)>>>"'Hello,world.'"str(1/7)>>>'0.14285714285714285'x = 10*3.25y  = 200*200s = '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...hello = 'hello,world\n'hellos = repr(hello)print(hellos)>>>'hello,world'

Output square cube table

# The just ust () method can be used to right the string and fill in spaces on the left. For I in range (1, 11): print (repr (x ). should ust (2), repr (x * x), should ust (3), end = '') print (repr (x * x ). must ust (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 72910 100 for x in range ): print ('{0: 2d} {1: 3d} {2: 4d }'. format (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 72910 100 1000

Str. format () usage:
{} And the characters in it will be replaced by parameters in format. The number in brackets is used to point to the position of the input object in format ().
For example

>>> print('{0} and {1}'.format('spam', 'eggs'))spam and eggs>>> print('{1} and {0}'.format('spam', 'eggs'))eggs and spam

If the keyword function is used in format (), their values point to the parameter using this name.

>>> print('This {food} is {adjective}.'.format(...       food='spam', adjective='absolutely horrible'))This spam is absolutely horrible.

Any combination of location and keyword Parameters

>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',                                                       other='Georg'))The story of Bill, Manfred, and Georg.

'! A' (use ascii ()),'! S '(use str () and '! R' (using repr () can be used to convert a value before formatting:

>>> 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.

Optional ":" and the format identifier can follow the field name. This allows better formatting of values. In the following example, the Pi is retained to the third digit after the decimal point:

import mathprint('{0:3f}'.format(math.pi))>>>3.142

Input an integer after ':' To ensure that the field has at least so many widths, which is useful for table beautification.

If you have a long formatted string that you do not want to separate, it is good to pass the variable name rather than the position during formatting.

The simplest thing is to input 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 use '**' before the table variable to implement the same function:

>>> 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
Format legacy strings
>>> import math>>> print('The value of PI is approximately %5.3f.' % math.pi)The value of PI is approximately 3.142.
Read and Write files

Open () returns a file object. The basic syntax format is as follows:
Open (filename, mode)
For example

F = open ('/tmp/workfile', 'w ')
The first parameter indicates the name of the file to be opened.
The second parameter describes the characters used in the file. Mode enables 'R' to be read-only. 'W' is only used for writing (if a file with the same name exists, it will be deleted ). 'A' is used to append the file content. Any written data will be automatically added to the end. 'r + 'is also used for reading and writing.
The mode parameter is optional, and 'R' is the default value.

File object method f. read ()

To read the content of a file, call f. read (size ).
Reads a certain amount of data and returns it as a string or Byte object.
Size is an optional numeric parameter.When the size is ignored or negative, all contents of the file will be read and returned.

f.read()>>>'This is the entire file.\n'
F. readline ()

Read a single row. If an empty string is returned, it indicates that the last row has been read.

>>> f.readline()'This is the first line of the file.\n'>>> f.readline()'Second line of the file\n'>>> f.readline()''
F. readlines ()

Returns all rows in the file.

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

Another way is to iterate a file object and 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 very simple, but does not provide a good control. Because they have different processing mechanisms, it is best not to mix them.

F. write ()

F. write (string) writes the string to the file, and then returns the number of characters written.

f.write('This is a test\n')>>>15

If the Written string is not a string, convert it first.

>>> value = ('the answer', 42)>>> s = str(value)>>> f.write(s)18
F. close ()

After processing a file, call f. close () to close the file and release system resources. If you try to call the file again, an exception is thrown.
You can also use the with statement. It will help you close the file correctly after the end, and it is shorter to write than try finally.

with open('/tmp/workfile','r') as f:    read_data = f.read()f.closed>>>True
Pickle Module

The pickle module of python implements basic data sequences and deserialization.
Through the serialization operation of the pickle module, we can save the information of objects running in the program to the file for permanent storage.
Through the deserialization operation of the pickle module, we can create the object stored in the last program from the file.

Basic interface:

pickle.dump(obj,file,[,protocol])

With the pickle object, you can open the file as a read:

X = pickle. load (file) # Read a string from file and refactor it to the original python object

File: class file object, with read () and readline () interfaces

Instance 1:

# Use the pickle module to save the data object to the File import pickledata1 = {'A': [1, 2.0, +], 'B' :( 'string ', u'unicode string') 'C': None} selfref_list = [1, 2, 3] selfref_list.append (selfref_list) output = open ('data. pk1', 'wb') pickle. dump (data1, output) pickle. dump (selfref_list, output,-1) output. close ()

Instance 2:

import pprint,picklepkl_file = open('data.pk1','rb')data1 = pickle.load(pk1_file)pprint.pprint(data1)data2 = pickle.load(pk1_file)pprint.pprint(data2)pkl_file.close()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.