Copyright: Without permission, please do not reprint without permission! ! ! https://blog.csdn.net/weixin_44755148/article/details/90901952
Python- module to create, call
- Module Definition
- Import module call
- ① use to write their own modules
- import + module name (we call file written above as an example)
- 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)
- ② import all functions, variables
- if __name__ == '__main__' statement
- ② use of another module
- Common attach two modules (random and csv) conventional usage
Module Definition
Action module: to store the program codes and data for use together again
Import module call
Encapsulated data files ending .py, you can use Pycharm, VS vode tools such new module file for storing data.
Jupyter notebook how to attach a file saved as .py file tips: %% writefile + module name (remember to .py as the file extension)
① use to write their own modules
import + module name (we call file written above as an example)
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)
② import all functions, variables
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
② 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
Common attach two modules (random and csv) conventional usage
random module common method
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']
读取完毕!