Fundamentals of Python: IO in Python

brief introduction

IO is input and output. If any program wants to interact with the outside world, it needs to use io. Compared with java, IO in Python is simpler and easier to use.

This article will introduce IO operations in Python in detail.

linux I / O

There are three standard inputs and outputs in linux: STDIN, STDOUT and STDERR. The corresponding numbers are 0, 1 and 2.

STDIN is standard input, and the information is read from the keyboard by default;

STDOUT is the standard output and outputs the output result to the terminal by default;

STDERR is a standard error and outputs the output result to the terminal by default.

We commonly use 2 > & 1 to specify standard output and standard error as the same output path.

Format output

In python, we can use the print method to output information.

Let's look at the definition of print function:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

The print function prints objects to the text stream specified by file, separated by sep and end at the end. If sep, end, file and flush exist, they must be given in the form of keyword parameters.

All non keyword parameters are converted to strings and written to the stream, separated by sep and end added at the end. Both sep and end must be strings; They can also be None, which means the default value is used. If no objects are given, print() will only write to end.

The file parameter must be an object with a write(string) method; If the parameter does not exist or is None, sys. Is used stdout. Since the parameters to be printed are converted to text strings, print() cannot be used for binary mode file objects. For these objects, you can use file write(...).

Whether the output is cached usually depends on file, but if the flush keyword parameter is true, the output stream will be forced to refresh.

You can see that the output format of print is relatively simple. Let's take a look at how to enrich the output format.

f format

If you want to format a string, you can add f or F before the beginning quotation mark of the string.

In this way, we can directly introduce the variable value into the string, just put the variable between {and}.

>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'

In addition to putting Python variables in {}, you can also put functions in it:

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.

Passing an integer after ':' can make the field the minimum character width. Convenient column alignment:

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...     print(f'{name:10} ==> {phone:10d}')
...
Sjoerd     ==>       4127
Jack       ==>       4098
Dcab       ==>       7678

The variable in {} can also be followed by the conversion symbol: '! a 'indicates application ascii(),'! s' indicates application str(), and '! r 'indicates application repr():

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

Format format

In addition, str comes with a powerful format function:

str.format(*args, **kwargs)

The string calling this method can contain string literals or substitution fields enclosed in curly braces {}. Each substitution field can contain a numeric index of a positional parameter or the name of a keyword parameter. Each replacement field in the returned string copy is replaced with the string value of the corresponding parameter.

>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'

Let's take another example of using an index:

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

Take a keyword example:

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

Let's take another example of combination:

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

There are also examples of very complex combinations:

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

Or use the '* *' symbol to pass table as a keyword parameter:

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

You can also format numbers using N type '{: n}':

>>> yes_votes = 42_572_654
>>> no_votes = 43_132_495
>>> percentage = yes_votes / (yes_votes + no_votes)
>>> '{:-9} YES votes  {:2.2%}'.format(yes_votes, percentage)
' 42572654 YES votes  49.67%'

repr and str

If we just want to convert Python objects to strings, we can use repr() or str (). The str () function is used to return a human readable representation of the value, and repr() is used to generate an interpreter readable representation.

for instance:

>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 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() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # The argument to repr() may be any Python object:
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"

The str object also provides some methods for manually formatting strings:

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # Note use of 'end' on previous line
...     print(repr(x*x*x).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

The str.rjust() method of the string object right aligns the string in a field of a given width by filling in spaces on the left. Similar methods include str.ljust() and str.center().

If the input string is too long, they will not truncate the string, but return it as it is.

If you want to guarantee the length of the string, you can use slice: x.ljust(n)[:n].

You can also use str.zfill() to fill the string with 0:

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

%Formatting method

%It can also be used to format strings. Given 'string'% values, the% instance in the string will be replaced with zero or more values elements. This operation is often referred to as string interpolation.

>>> import math
>>> print('The value of pi is approximately %5.3f.' % math.pi)
The value of pi is approximately 3.142.

Read write file

The file reading in python is very simple, just use the open() method.

open() returns a file object. Let's take a look at its definition:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

The first parameter is the file name.

The second parameter is the file opening mode. The available modes are:

charactersignificance
'r'Read (default)
'w'Write and truncate the file first
'x'Exclusive creation fails if the file already exists
'a'Write, append at the end if the file exists
'b'binary mode
't'Text mode (default)
'+'Open for update (read and write)

The default mode is' r '.

Take an example of an open file:

>>> f = open('workfile', 'w')
Copy code

When the file is opened, it naturally needs to be closed, so we need to call the f.close() method:

>>> f.close()
Copy code

Is there an automatic file closing function similar to try with resource in java?

We can use with, so that the file will be automatically closed after use, which is very easy to use.

>>> with open('workfile') as f:
...     read_data = f.read()

>>> # We can check that the file has been automatically closed.
>>> f.closed
True
 Copy code

After the file is closed, if you want to read it again, an error will be reported:

>>> f.close()
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
Copy code

Method of file object

After getting the file object, we can call the methods in the file.

f.read(size) reads some data and returns it as a string (in text mode) or a byte string object (in binary mode).

Size is an optional numeric parameter. When size is omitted or negative, the contents of the whole file will be read and returned; When other values are taken, up to size characters (in text mode) or size bytes (in binary mode) are read and returned. If the end of the file has been reached, f.read() will return an empty string ('').

>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
Copy code

f. Readline() reads a line from the file; The newline character (\ n) is left at the end of the string. If the file does not end with a newline character, it is omitted on the last line of the file. If f.readline() returns an empty string, it indicates that the end of the file has been reached, while the empty line uses' \ n 'to indicate that the string contains only one newline character.

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

There is also a simpler reading method, which is to traverse from the file:

>>> for line in f:
...     print(line, end='')
...
This is the first line of the file.
Second line of the file
 Copy code

If you want to read all the lines in the file as a list, you can also use list(f) or f.readlines().

f.write(string) writes the contents of the string to the file and returns the number of characters written.

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

If you are in text mode, you need to convert the object into text form before writing the file. We can use str() to convert it.

>>> value = ('the answer', 42)
>>> s = str(value)  # convert the tuple to string
>>> f.write(s)
18
 Copy code

Use f.seek (offset, where) to locate the position of the file pointer, and then read from this position.

The 0 value of where indicates that it is calculated from the beginning of the file, 1 indicates that the current file location is used, and 2 indicates that the end of the file is used as the reference point. Where if omitted, the default value is 0, that is, the beginning of the file is used as the reference point.

>>> f = open('workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)      # Go to the 6th byte in the file
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2)  # Go to the 3rd byte before the end
13
>>> f.read(1)
b'd'
Copy code

Using json

JSON is a convenient file format for information exchange. Let's look at how to use JSON to convert objects to Strings:

>>> import json
>>> json.dumps([1, 'simple', 'list'])
'[1, "simple", "list"]'
Copy code

dumps is to convert an object to json str. json also has a dump method, which can store objects directly into files.

json.dump(x, f)
Copy code

To parse the json string from the file, use load:

x = json.load(f)
Copy code

Keys in key value pairs in JSON are always of type str. When an object is converted to JSON, all keys in the dictionary are cast to strings. As a result, when the dictionary is converted to JSON and then converted back to the dictionary, it may not be equal to the original. In other words, if x has a non string key, there are loads (dumps (x))= x.

Keywords: Python Back-end

Added by WRa on Fri, 07 Jan 2022 15:27:25 +0200