Basics of Python: IO in Python

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 input and output

There are three standard input and output in linux, namely STDIN, STDOUT, STDERR, the corresponding numbers are 0, 1, 2.

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

STDOUT is the standard output, and the output results are output to the terminal by default;

STDERR is standard error, and the output is output to the terminal by default.

The commonly used 2>&1 refers to specifying the standard output and standard error as the same output path.

formatted output

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

Let's look at the definition of the 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 with end at the 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, split by sep with end appended at the end . Both sep and end must be strings; they can also be None, which means the default values ​​are used. If no objects is given, only endprint() will be written .

The file parameter must be an object with a write(string)method ; Nonewill be used if the parameter does not exist or is sys.stdout. print()Cannot be used with binary mode file objects since the arguments to be printed are converted to text strings . 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 be flushed.

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

fformat

If you want to format the string, you can add for F.

In this way, we can directly introduce the variable value in 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 a value conversion symbol: '!a'it means application ascii(), '!s'means application str(), and '!r'means 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 itself comes with a powerful format function:

str.format(*args, **kwargs)

The string on which this method is called may contain string literals or curly brace- {}enclosed replacement fields, each of which may contain the numerical index of a positional argument, or the name of a keyword argument. 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'

Here's another example using indexes:

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

See an example of a keyword:

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

Let's look at another example of composition:

>>> 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 '**' notation to pass table as a keyword argument:

>>> 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 use the 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%'

repr and str

If we just want to convert a Python object to a string, we can use repr()either or str(), str()function is used to return a human-readable representation of the value, but repr()is used to generate an interpreter-readable representation.

for 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', '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()methods right-justify strings in fields of a given width by padding with spaces on the left. There are similar methods str.ljust()and str.center().

If the input string is too long, they don't truncate the string, but return it as-is.

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

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

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

%Format method

% can also be used to format strings, given that'string' % values instances in are replaced with zero or more elements . This operation is often referred to as string interpolation.string%values

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

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

open()will return 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 filename.

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

character significance
'r' read (default)
'w' write, and truncate the file first
'x' Exclusive create, fail if file already exists
'a' write, append at the end if the file exists
'b' binary mode
't' text mode (default)
'+' Open for updates (read and write)

The default mode is 'r'.

See an example of an open file:

>>> f = open('workfile', 'w')
复制代码

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

>>> f.close()
复制代码

Is there a function of automatically closing files 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
复制代码

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

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

methods of the file object

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

f.read(size)Some data is read and returned as a string (in text mode) or a bytes object (in binary mode).

size is an optional numeric parameter. When size is omitted or negative, the contents of the entire file are 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 ). f.read()Returns an empty string ( '') if the end of the file has been reached .

>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
复制代码

f.readline()Read a line from the file; the newline character ( \n) is left at the end of the string, or omitted on the last line of the file if the file does not end with a newline character. If an empty string is f.readline()returned , the end of the file has been reached, and an empty line is '\n'indicated with a , 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()
''
复制代码

There is also a simpler way to read, which is to iterate from the file:

>>> for line in f:
...     print(line, end='')
...
This is the first line of the file.
Second line of the file
复制代码

You can also use list(f)or f.readlines().

f.write(string)Will write the contents of string to the file and return the number of characters written.

>>> f.write('This is a test\n')
15
复制代码

If it is in text mode, before writing to the file, the object needs to be converted into text form, which we can use str()to convert.

>>> value = ('the answer', 42)
>>> s = str(value)  # convert the tuple to string
>>> f.write(s)
18
复制代码

Use f.seek(offset, whence)the location where the file pointer can be located, and subsequent reads will start from that location.

A value of 0 for whence means counting from the beginning of the file, 1 means using the current file position, and 2 means using the end of the file as the reference point. whence is omitted and defaults to 0, i.e. using the beginning of the file 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'
复制代码

use json

JSON is a file format that is very convenient for information exchange. Let's see how to use JSON to convert an object to a string:

>>> import json
>>> json.dumps([1, 'simple', 'list'])
'[1, "simple", "list"]'
复制代码

dumps is to convert object to json str. JSON also has a dump method, which can directly store objects in a file.

json.dump(x, f)
复制代码

To parse out the json string from the file, you can use load:

x = json.load(f)
复制代码

Keys in key-value pairs in JSON are always of strtype . When an object is converted to JSON, all keys in the dictionary are coerced to strings. The consequence of this is that the dictionary converted to JSON and then back to the dictionary may not be equal to the original. In other words, if x has a key that is not a string, there is loads(dumps(x)) != x.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324688323&siteId=291194637