Input and Output

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.

7.1. Fancier Output Formatting

  • the standard output file can be referenced as sys.stdout.

    1
    2
    3
    >>> sys.stdout.write('Hello\n')
    Hello
    6
  • Formatted string literally, add f or F before a single or triple quotation, wrap variable or expression in {}

    1
    2
    3
    4
    5
    >>> a = 2021
    >>> b = 'Python'
    >>> s = f'Learn {b} in {a}'
    >>> s
    'Learn Python in 2021'
  • str.format() can make more complex format

  • using string slicing and concatenation operations to create any layout you can imagine.

  • you can convert any value to a string with the repr() or str() functions.

7.1.1. Formatted String Literals

  • Passing an integer after the : will cause that field to be a minimum number of characters wide. This is useful for making columns line up.

    1
    2
    3
    4
    5
    6
    >>> f'the res is {res:<20}|'
    'the res is 3.423452154 |'
    >>> f'the res is {res:^20}|'
    'the res is 3.423452154 |'
    >>> f'the res is {res:>20}|'
    'the res is 3.423452154|'
  • Other modifiers can be used to convert the value before it is formatted. !a applies ascii(), !s applies str(), and !r applies repr():

    1
    2
    3
    4
    5
    >>> animals = 'eels'
    >>> print(f'My hovercraft is full of {animals}.')
    My hovercraft is full of eels.
    >>> print(f'My hovercraft is full of {animals!r}.')
    My hovercraft is full of 'eels'.
  • see more at Format Specification Mini-Language

7.1.2. The String format() Method

  • A number in the brackets can be used to refer to the position of the object passed into the str.format() method.

    1
    2
    >>> print('{1} and {0}'.format('spam', 'eggs'))
    eggs and spam
  • keyword arguments are referred by their keys

    1
    2
    3
    >>> print('This {food} is {adjective}.'.format(
    ... food='spam', adjective='absolutely horrible'))
    This spam is absolutely horrible.
  • dictionary unpacking is useful

    1
    2
    3
    >>> dic = {'name' : 'Jack' , 'age':24}
    >>> 'His name is {name} and age is {age}'.format(**dic)
    'His name is Jack and age is 24'

    7.1.3. Manual String Formatting

  • The str.rjust() method of string objects right-justifies a string in a field of a given width by padding it with spaces on the left, similar methods are str.ljust() and str.center().

  • They just return a new string

  • They do not truncate strings, if you really want to truncate surplus part, use x.ljust(n)[:n] to make a slicing.

    1
    2
    3
    4
    5
    6
    >>> 'hello'.rjust(10)
    ' hello'
    >>> 'hello'.ljust(10)
    'hello '
    >>> 'hello'.center(10)
    ' hello '
  • str.zfill(), which pads a numeric string on the left with zeros. It understands about plus and minus signs:

    1
    2
    3
    4
    5
    6
    >>> '12'.zfill(5)
    '00012'
    >>> '-3.14'.zfill(7)
    '-003.14'
    >>> '3.14159265359'.zfill(5)
    '3.14159265359'

    7.1.4. Old string formatting

  • Given 'string' % values, instances of % in string are replaced with zero or more elements of values.

    (This method is very C like)

    1
    2
    3
    4
    5
    >>> import math
    >>> print('The value of pi is approximately %5.3f.' % math.pi)
    The value of pi is approximately 3.142.
    >>> print('a = %d b = %f' % (2000,3.14))
    a = 2000 b = 3.140000
  • see more at printf-style String Formatting

7.2. Reading and Writing Files

  • file = open('filename' , 'mode'), The mode argument is optional; 'r' will be assumed if it’s omitted.

  • when I/O text encoding can be specified, If encoding is not specified, the default is platform dependent (see open())

  • add 'b'to mode character to I/O binary, which represented by bytes objects in Python

  • In text mode, the default when reading is to convert platform-specific line endings, you write the \n in your source code, but Unix Python use \n, Windows Python use \r\n, when actually write to the file.

  • The advantage of using with is that the file is properly closed after its suite finishes, even if an exception is raised at some point.

    If the do file.write() without file closing, the content may not be writen to the disk,even Python exit successfully!!!

7.2.1. Methods of File Objects

  • f.read(size), size is a numerical number, the method reads size character in text mode, reads size bytes in binary mode, if not given, read the whole file.

    It will read from the latest position! Return a ‘’ when reach the end

    1
    2
    $ cat text
    HelloWorld
    1
    2
    3
    4
    5
    6
    7
    8
    9
    >>> f = open ('text' , 'rt')
    >>> f.read(5)
    'Hello'
    >>> f.read(5)
    'World'
    >>> f.read(5)
    '\n'
    >>> f.read(5)
    ''
  • 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. Return a '' when reach the end of the file.

    1
    2
    3
    4
    5
    6
    >>> f.readline()
    'This is the first line of the file.\n'
    >>> f.readline()
    'Second line of the file\n'
    >>> f.readline()
    ''
  • use list(f) or f.readlines() to read as a list, or directly use a loop

    1
    2
    3
    4
    5
    >>> for line in f:
    ... print(line, end='')
    ...
    This is the first line of the file.
    Second line of the file
  • f.write(string) writes the contents of string to the file, returning the number of characters written.

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

    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

  • 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(should only be used to pass to a seek(), otherwise meaningless) when in text mode.

  • f.seek(offset, whence). The position is computed from adding offset to a reference point; the reference point is selected by the whence argument.

    whence = (default is 0) position
    0 beginning of the file
    1 current position
    2 end of the file
  • In text mode, only seeks relative to the beginning of the file are allowed, only the return value of tell() or 0 is a valid value for whence.

7.2.2. Saving structured data with json

When you want to save more complex data types like nested lists and dictionaries, parsing and serializing by hand becomes complicated.

  • The standard module called 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.

  • If you have an object x, you can view its JSON string representation with a simple line of code:

    1
    2
    3
    4
    5
    6
    7
    >>> import json
    >>> ls = ['ewf',123]
    >>> s= json.dumps(ls)
    >>> s
    '["ewf", 123]'
    >>> type(s)
    <class 'str'>
  • dump(), simply serializes the object to a text file. So if f is a text file object opened for writing

    1
    2
    >>> with open('serialization','w+') as f:
    ... json.dump(ls,f)
    1
    2
    3
    $ cat serialization 
    ["ewf", 123]%
    # (% means no newline)
  • To decode the object again, if f is a text file object which has been opened for reading

    1
    2
    3
    4
    5
    6
    7
    >>> f = open('serialization')
    >>> import json as j
    >>> x = j.load(f)
    >>> x
    ['ewf', 123]
    >>> type(x)
    <class 'list'>
  • to convert Python Class to json see more at json

  • pickle is a protocol which allows the serialization of arbitrarily complex Python objects, and it is specific to Python Only.

    deserializing pickle data coming from an untrusted source can execute arbitrary code!!!