Introduction to the

IO is the input and output, and any program that wants to interact with the outside world needs to use IO. IO in Python is much simpler and easier to use than Java.

This article takes a closer look at IO operations in Python.

Linux I/O

There are three types of standard input and output in Linux: STDIN, STDOUT, and STDERR. The numbers are 0, 1, and 2.

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

STDOUT is standard output. By default, STDOUT output results to the terminal.

STDERR is a standard error that prints the output to the terminal by default.

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

Formatted output

In Python, we can use the print method to print information.

Let’s look at the definition of the print function:

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

The print function prints objects to the text stream specified by file, separated by sep and followed by end. Sep, end, file, and flush, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings and written to the stream, separated by sep, with an end appended to the end. Both sep and end must be strings; They can also be None, which means the default is used. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; If the argument does not exist or is None, sys.stdout will be used. Because arguments to print are converted to text strings, print() cannot be used for file objects in binary mode. For these objects, you can use file.write(…) .

Whether the output is cached is usually determined by file, but if the flush keyword argument is true, the output stream is forced to flush.

As you can see, the output format of print is relatively simple. Let’s look at how to format the output.

F the formatting

If you want to format a string, you can precede the opening quotation mark with either f or f.

This way, we can introduce variable values directly into the string by placing them between {and}.

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

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

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

Passing an integer after the ‘:’ makes the field the minimum character width. Facilitate 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
Copy the code

Variables in {} can also be followed by the conversion symbol: ‘! A ‘applies ASCII (), ‘! S ‘applies STR (), and ‘! R ‘applies 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'.
Copy the code

The format to format

In addition, STR comes with a powerful format function:

str.format(*args, **kwargs)
Copy the code

The string that calls this method can contain either a string literal or a substitution field enclosed in curly braces {}, each of which can contain a numeric index of a positional argument, or the name of a keyword argument. Each replacement field in the returned copy of the string 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'
Copy the code

Let’s look at another example of using indexes:

>>> print('{0} and {1}'.format('spam'.'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam'.'eggs'))
eggs and spam
Copy the code

Look at an example of a keyword:

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

Here’s another example of a combination:

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

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
Copy the code

Or pass table as a keyword argument using the ‘**’ symbol:

>>> 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
Copy the code

You can also use n type ‘{:n}’ to format numbers:

>>> 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%'
Copy the code

Repr and STR

If we just want to convert Python objects to strings, we can use repr() or STR (), where the STR () function is used to return human-readable representations of values, and repr() is used to generate interpreter-readable representations.

Here’s an example:

>>> 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 ', 'dense eggs))"
Copy the code

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
Copy the code

The str.rjust() method of a string object right-aligns the string in a field of a given width by padding space to the left. Similar methods include str.ljust() and str.center().

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

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

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

>>> '12'.zfill(5)
'00012'
>>> '3.14'.zfill(7)
'003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'
Copy the code

% format method

% can also be used to format strings. Given ‘string’ % values, the % instance in 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.3 F.' % math.pi)
The value of pi is approximately 3.142.
Copy the code

Read and write files

Reading files in Python is very simple, using the open() method.

Open () returns a file object. Let’s look at its definition:

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

The first parameter is the file name.

The second parameter is the mode in which the file is opened. The available modes are:

character meaning
'r' Read (default)
'w' Write, and truncate the file first
'x' Exclusive creation fails if the file already exists
'a' Write, appended to the end if the file exists
'b' Binary mode
't' Text mode (default)
'+' Open for update (read and write)

The default mode is ‘r’.

Look at an example of an open file:

>>> f = open('workfile'.'w')
Copy the code

The file is open and naturally needs to be closed, so we need to show that we call f.close() :

>>> f.close()
Copy the code

Is there an automatic file closing function like the Try with Resource in Java?

We can use with, so the file will be closed automatically after use, very useful.

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

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

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

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

File object method

Once we get 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 object (in binary mode).

Size is an optional numeric parameter. When size is omitted or negative, the entire contents of the file are read and returned; When taking other values, 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() returns an empty string (“).

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

F.readline () reads a line from the file; The newline character (\n) is left at the end of the string and omitted on the last line of the file if the file does not end in a newline. If f.readline() returns an empty string, the end of the file has been reached, while the empty line is represented by ‘\n’, and the string contains only a newline.

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

An even simpler way to read is to traverse the file:

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

If you want to read all the lines in a 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 to be written.

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

If you are in text mode, you need to convert the object to text before writing to the file. You can use STR () to do this.

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

Use f.seek(offset, whence) to locate the position of the file pointer, from which subsequent reads will start.

A value of 0 at whence means counting from the beginning of the file, 1 means using the current file location, and 2 means using the end of the file as a reference point. whence defaults to 0 if omitted, using the beginning of the file as a 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 the code

Using json

JSON is a convenient file format for information exchange. Let’s see how we can use JSON to convert objects to strings:

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

Dumps is a translation of an object to JSON STR. Json also has a dump method to store objects directly to a file.

json.dump(x, f)
Copy the code

To parse out a JSON string from a file, use load:

x = json.load(f)
Copy the code

The key in a KEY-value pair in JSON is always of type STR. When an object is converted to JSON, all keys in the dictionary are cast to strings. The result is that the dictionary may not be the same as the original when it is converted to JSON and then back to the dictionary. In other words, loads(dumps(x)) are present if X has non-string keys! = x.


This article is available at www.flydean.com/08-python-i…

The most popular interpretation, the most profound dry goods, the most concise tutorial, many tips you didn’t know waiting for you to discover!

Welcome to pay attention to my public number: “procedures those things”, understand technology, more understand you!