Python- module to create, call

Copyright: Without permission, please do not reprint without permission! ! ! https://blog.csdn.net/weixin_44755148/article/details/90901952

Module Definition

Action module: to store the program codes and data for use together again
Here Insert Picture Description

Import module call

Encapsulated data files ending .py, you can use Pycharm, VS vode tools such new module file for storing data.
Here Insert Picture Description
Jupyter notebook how to attach a file saved as .py file tips: %% writefile + module name (remember to .py as the file extension)
Here Insert Picture Description

① use to write their own modules

import + module name (we call file written above as an example)

Here Insert Picture Description

from ... import ... statement: allows you to import a specified part from the module to the current module
① designated import function method (do not write the module name when calling)

Here Insert Picture Description

② import all functions, variables

Here Insert Picture Description

IF name == ' main ' statement

The first case: the main module (that is, calling module) occurred in the program, call the normal operation of the
second case: appears in the imported module, behind the content of the article statement will not be executed
Here Insert Picture Description
Here Insert Picture Description

② use of another module

Corresponding to first install the library (python interpreter and requires pre PIP)
Windows用户输入:pip install + 模块名

苹果电脑输入:pip3 install + 模块名
For more information on using dir () function View module

Here Insert Picture Description
Here Insert Picture Description

Common attach two modules (random and csv) conventional usage

random module common method

Here Insert Picture Description

csv module to read and write files

#创建并写入文件     csv.writer()
import csv       #
with open('F:\\猫看见\\猫看见\\Python代码\\test.csv','a',newline = '',encoding='utf-8') as f:
    writer  = csv.writer(f)
    writer.writerow(['4', '猫砂', '25', '1022', '886'])     #只能单条数据进行写入
    writer.writerow(['5', '猫罐头', '18', '2234', '3121'])
#读取文件          csv.reader()
import csv

with open("F:\\猫看见\\猫看见\\Python代码\\test.csv",newline = '')  as f:
    reader = csv.reader(f)
    #使用csv的reader()方法,创建一个reader对象
    for row in reader: 
    #遍历reader对象的每一行
        print(row)

print("读取完毕!")

#结果展示
['4', '猫砂', '25', '1022', '886']
['5', '猫罐头', '18', '2234', '3121']
读取完毕!

Guess you like

Origin blog.csdn.net/weixin_44755148/article/details/90901952