You have to secretly learn Python, and then stun everyone (fourth day)

Article Directory

  • Preface What is a module? Import your own module with me Step 1: Create a new module Step 2: Call the module Call different methods of the module. if __name__ == '__main__'What module should I use for the csv module to operate Excel charts? What is in this module? Using the csv module to read and write I drew a circle, welcome everyone to our small circle

foreword

Early review: You have to learn Python secretly, and then stun everyone (the third day) The above article contains some knowledge bases of python, mainly about Python’s reading and writing operations on files, which may be due to the relatively small number of words. Every time I click on it, I feel a little awkward. But it is also because the reading and writing of files will be more difficult than the previous two articles.

So today, we'll take a look at what makes Python a 'panacea', modules! If you are not very proficient in the basics, you can build a solid foundation. After all, a tall building is built on the ground, and it is very dangerous to have a dishonest foundation.

本系列文默认各位有一定的C或C++基础,因为我是学了点C++的皮毛之后入手的Python。
本系列文默认各位会百度,学习‘模块’这个模块的话,还是建议大家有自己的编辑器和编译器的,上一篇已经给大家做了推荐啦?

本系列也会着重培养各位的自主动手能力,毕竟我不可能把所有知识点都给你讲到,所以自己解决需求的能力就尤为重要,所以我在文中埋得坑请不要把它们看成坑,那是我留给你们的锻炼机会,请各显神通,自行解决。
1234567

If you encounter difficulties in learning and want to find a python learning and communication environment, you can join our python group, follow the editor, and private message "01" to join the group and receive python learning materials, which will save a lot of time and reduce many problems you encounter.

Ok, let's get to the point.

What are modules?

Anyone who has learned other high-level languages ​​will know that at the beginning of a C/C++ source file, there are usually a lot of 'include', which refer to header files. There are some classes, functions, variables, etc. in a header file. If you want to use these things, you need to make a statement in advance.

This is really too general.

img

Suppose there is a QQ group now, there are members, documents and chat records in the group, and you want to obtain and use these things, do you have to join the group? This is the reason for using modules. There are classes, functions, and variables in modules. If you want to use these things, you have to import modules.

It's much easier to say that.

emmm, I always feel that there is still something missing. Yes, let’s scan a module, just take a look at it, don’t ask to understand, I probably know what’s inside, we have an idea:

The following is an interception from a piece of random module:

from warnings import warn as _warn
from types import MethodType as _MethodType, BuiltinMethodType as _BuiltinMethodType
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
from os import urandom as _urandom
from _collections_abc import Set as _Set, Sequence as _Sequence
from hashlib import sha512 as _sha512
import _random

__all__ = ["Random","seed","random","uniform","randint","choice","sample",
           "randrange","shuffle","normalvariate","lognormvariate",
           "expovariate","vonmisesvariate","gammavariate","triangular",
           "gauss","betavariate","paretovariate","weibullvariate",
           "getstate","setstate", "getrandbits",
           "SystemRandom"]

NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0)
TWOPI = 2.0*_pi
LOG4 = _log(4.0)
SG_MAGICCONST = 1.0 + _log(4.5)
BPF = 53        # Number of bits in a float
RECIP_BPF = 2**-BPF

class Random(_random.Random):
    VERSION = 3     # used by getstate/setstate

    def __init__(self, x=None):
        self.seed(x)
        self.gauss_next = None

    def seed(self, a=None, version=2):
        if a is None:
            try:
                # Seed with enough bytes to span the 19937 bit
                # state space for the Mersenne Twister
                a = int.from_bytes(_urandom(2500), 'big')
            except NotImplementedError:
                import time
                a = int(time.time() * 256) # use fractional seconds

        if version == 2:
            if isinstance(a, (str, bytes, bytearray)):
                if isinstance(a, str):
                    a = a.encode()
                a += _sha512(a).digest()
                a = int.from_bytes(a, 'big')

        super().seed(a)
        self.gauss_next = None
……
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950

It can be seen that at the beginning, it adjusted a bunch of packages (import..., it doesn't matter if you don't understand it now), and then there are some variables, and then a class, and there are functions in the class. Okay, just take a quick glance, let's move on

You need to use assignment statements to define variables, you need to use def statements to encapsulate functions, you need to use class statements to encapsulate classes, but you don’t need any statements to encapsulate modules.

The reason why no statement is used is because each separate Python code file (file with the suffix .py) is a separate module.

This is not difficult to understand.

The purpose of encapsulating modules is also to store program code and data for reuse. If it is encapsulated into classes and functions, it is mainly convenient for ourselves to call, but with encapsulated modules, we can not only use them ourselves, but also share them with others in a file format.

Follow me to import your own modules

How should I put it, there are tens of thousands of other people's modules, but it is more handy to use the modules written by myself when learning, because in the future, I will inevitably write modules by myself.

Step 1: Create a new module

img

According to the order in the figure, create a new module, and then write the code.

Step 2: Call the module

img

Well, this is a very simple little chestnut.

Call different methods of the module.

Just like the previous article, there are two ways to open a file, one is to open directly, and the other is to use an alias. There are also different ways to call modules here.

The first type of direct import has already been seen, but here is another point. If the module name is too long, you can use an alias, such as import test. You think test is a bit long and it is inconvenient to use later. You can do this: import test as t. However, you can only use t to refer to the module later, and you can no longer use test. It has been packaged.

The second method is called from...import... What is this method, or the example above, I want to use the test3 class in the test now, I don’t want the others, so why should I import other things in, isn’t that too huge? At this time, this method can be used for precise positioning.

Look at the picture: This is a typical wrong wording: Now that you have accurately positioned, don’t get entangled with the big pool before

img

Here is a test to see whether there will be conflicts if only a certain part is imported, and the other parts that are not imported are imported into some applications:

img

Here is the verification result:

img

This is the use of aliases, which can still be used:

img

One more point here, what if you want to import multiple modules? It’s also possible, just use a comma to separate different modules, let’s get moving and try it out for ourselves.

if name == ‘main

For Python and many other programming languages, the program must have a run entry.

In Python, when we are running a certain py file, we can start the program --- this py file is the running entry of the program.

However, when we have a lot of py files to form a program:

img
In order to [specify] that a certain py file is the running entry of the program, we can write such code in the py file:

# 【文件:xx.py】

代码块 ①……

if __name__ == '__main__':
    代码块 ②……
123456

This sentence means something like this:

img

[if name == ' main '] here is equivalent to the program entry of Python simulation. Python itself does not stipulate to write this way, this is a coding habit that programmers agree on.

The csv module operates Excel charts

First of all, we need to know clearly that this is using other people's modules. Secondly, we only know that the function we want to achieve is to simply operate the Excel table.

Then our order should be: What module should I use? What functions are in this module? How to use these specific functions? OK, I'm going to use it.

What module should I use?

This is actually very easy to handle, but also very difficult to handle. It's easy to handle, just ask Du Niang:

img

Yes, you can find them all in one search. Let’s say it’s hard to do. You can’t find many experiences of predecessors, so you have to ask.

For example, we use the csv module today because it is simple and easy to use.

What's in this module?

Well, this question is also easy to solve. If you feel that you have no problem with English, or if you want to practice your English, you can go to the official website, because the official website has been updated to the latest version. The Chinese translation version, sometimes it is not very effective to find the latest version.

Hey, just kidding, the Chinese version also has a Python manual (official Chinese version)

Ok, we found the csv module (with a search box): CSV

If you are interested, you can read it in both Chinese and English. If you are in a hurry, just look at its sample code.

Using the csv module

First we create a table:

img

Then open this table, just like opening a file. If you are not proficient in file operations, you can go back to this review: You have to learn Python secretly (3)

read

import csv

with open('test.csv', newline = '', encoding = 'GBK')  as f:
    #参数encoding = 'utf-8'防止出现乱码
    reader = csv.reader(f)
    #使用csv的reader()方法,创建一个reader对象
    for row in reader:
        print(row)
12345678

img

Write

First create an instance of a variable named writer (or other names), the creation method is writer = csv.writer(x), and then use writer.writerow(list) to write the contents of a row list to the csv file.

img

import csv

with open('test.csv','a', newline='',encoding='utf-8') as f:
    writer  = csv.writer(f)
    writer.writerow(['6', '小黑', '65', '82', '86'])
    writer.writerow(['7', '小红', '78', '64', '31'])
123456

img

img
So far, we have learned the most basic methods of reading and entering csv tables.

Today's task: Let's try to merge multiple csv files into one csv file. This is not difficult to say, and it is not so intuitive to say simple.

Welcome to the Python community

If you have any difficulties in learning python and don’t understand, you can scan the CSDN official certification QR code below on WeChat to join python exchange learning, exchange questions, and help each other. There are good learning tutorials and development tools here.

insert image description here

Guess you like

Origin blog.csdn.net/libaiup/article/details/131827099