一奋早、模塊的使用
1. 模塊使用說(shuō)明
python中一個(gè)py文件就是一個(gè)模塊误堡,
可以通過(guò)import 或者 from - import在一個(gè)模塊中去使用另一個(gè)模塊的內(nèi)容
import 模塊名
---> 將模塊中所有的內(nèi)容都導(dǎo)入譬挚,并且可以在當(dāng)前模塊中通過(guò)“模塊名.”的方式去使用所有的全局變量
(推薦奸绷,可以從代碼中看出來(lái)是從哪個(gè)模塊中導(dǎo)入的)from 模塊名 import 變量1,變量2借浊,……
--> 將模塊中所有的內(nèi)容都導(dǎo)入塘淑,但是只能使用import后面的變量from 模塊名 import *
--> 將模塊中所有的內(nèi)容都導(dǎo)入,可以直接使用模塊中所有的變量
代碼執(zhí)行到import的時(shí)候蚂斤,會(huì)將import后面的模塊的內(nèi)容執(zhí)行一遍
例:
# import test1
# # 100
# # 這是test1中的內(nèi)容
# # hello test1
#
# print(test1.test_a + 1) # 101
# test1.test1_func1() # hello test1
test1.py中代碼如下:
test_a = 100
print(test_a)
print('這是test1中的內(nèi)容')
def test1_func1():
print('hello test1')
test1_func1()
# from test1 import test_a
# print('當(dāng)前模塊:', test_a)
# print('當(dāng)前模塊:', test_func1) # NameError: name 'test_func1' is not defined
# from test1 import test1_func1, test_a
# # 100
# # 這是test1中的內(nèi)容
# # hello test1
#
# test1_func1() # hello test1
# from test1 import *
# # 100
# # 這是test1中的內(nèi)容
# # hello test1
# test1_func1() # hello test1
2.重命名
import 模塊嗎 as 模塊的新名字 (給模塊重命名存捺,使用的時(shí)候使用新的名字)
from 模塊名 import 變量名1 as 新名1, 變量名2曙蒸,…… (給部分變量重新命名)
# import test1 as TS
# # 100
# # 這是test1中的內(nèi)容
# # hello test1
#
# TS.test1_func1() # hello test1
# from test1 import test_a as ts_a
# test_a = 50
# # 100
# # 這是test1中的內(nèi)容
# # hello test1
# print(ts_a + 1) # 101 (使用test1模塊的test_a變量)
# print(test_a) # 50 (當(dāng)前模塊的test_a變量)
3.import:
可以檢查被導(dǎo)入的內(nèi)容之前是否已經(jīng)導(dǎo)入過(guò)捌治,如果導(dǎo)入過(guò),不會(huì)再重復(fù)導(dǎo)入纽窟,但是多種導(dǎo)入的效果可以同時(shí)生效
# 導(dǎo)入多次肖油,但是只執(zhí)行一次,多種導(dǎo)入的效果可以同時(shí)生效
# import test1
# import test1
# from test1 import test1_func1 as ts_a
# # 100
# # 這是test1中的內(nèi)容
# # hello test1
#
# test1.test1_func1() # hello test1
# ts_a() # hello test1
二、選擇性導(dǎo)入(阻止導(dǎo)入)
1.阻止導(dǎo)入的方法:
if __name__ == ‘__main__':
代碼塊
說(shuō)明:
if __name__ == ‘__main__':
--> 固定寫(xiě)法
代碼塊 --> 直接執(zhí)行當(dāng)前模塊臂港,代碼塊會(huì)被執(zhí)行森枪,如果在別的模塊中被導(dǎo)入,代碼塊不會(huì)執(zhí)行
test1.py中代碼:
def test1_func1():
print('hello test1')
if __name__ == '__main__':
test_a = 100
print(test_a)
print('這是test1中的內(nèi)容')
test1_func1()
import test1
# 沒(méi)有打印
test1.test1_func1() # hello test1
# test1.test_a在阻止導(dǎo)入代碼塊中审孽,不會(huì)導(dǎo)入
# print(test1.test_a) # AttributeError: module 'test1' has no attribute 'test_a'
2.阻止導(dǎo)入語(yǔ)句的原理
每一個(gè)模塊都有一個(gè) name 屬性县袱,這個(gè)屬性的默認(rèn)值是當(dāng)前模塊對(duì)應(yīng)py文件的文件名,
當(dāng)當(dāng)前模塊正在被執(zhí)行(直接)的時(shí)候佑力,系統(tǒng)會(huì)自動(dòng)將模塊的name屬性變成'main'
import test1
print(__name__) # __main__
print(test1.__name__) # test1
3.什么時(shí)候使用模塊
將具有相同的功能的函數(shù)和數(shù)據(jù)封裝到一起
三式散、迭代器
1.什么是迭代器(iter)
迭代器是python中一種容器類的數(shù)據(jù)類型,屬于序列打颤。沒(méi)有具體的字面量杂数,
可以將其他的序列轉(zhuǎn)換成迭代器: iter(序列)
2.迭代器的特點(diǎn)
只能通過(guò)next方法去一個(gè)一個(gè)地按順序獲取迭代器中的元素,取出后迭代器中就不存在這個(gè)元素了
print(iter([5, 6, 7])) # <list_iterator object at 0x00000000025EB2B0>
iter1 = iter('abc')
print(iter1) # <str_iterator object at 0x00000000024E28D0>
print(next(iter1)) # a
print(next(iter1)) # b
print(next(iter1)) # c
# print(next(iter1)) # StopIteration
3.遍歷迭代器
print('===============')
iter1 = iter(['abc', 1, 'name'])
for x in iter1:
print(x)
# abc
# 1
# name
next(迭代器)
迭代器.next()
iter2 = iter((1, 2, 3))
a = iter2.__next__()
print(a) # 1
print(next(iter2)) # 2
list1 = list(iter2)
print(list1) # [3]
四瘸洛、生成式和生成器
1.什么是生成器
生成器就是迭代器揍移,但是迭代器不一定是生成器
生成式就是生成器的一種特殊形式:(變量 for 變量 in 序列)
例:產(chǎn)生一個(gè)生成器,生成器中可以生成的數(shù)據(jù)是數(shù)字0~4(每個(gè)元素是數(shù)字)
ge1 = (x for x in range(5))
print(ge1)
print(next(ge1))
print(next(ge1))
print('=========')
for item in ge1:
print(item)
ge2 = (x*2 for x in range(5))
print('=========')
for item in ge2:
print(item)
ge2 = ([x, x*2] for x in 'abc')
print(next(ge2))
print('===========')
ge2 = (x for x in range(5) if x%2)
for item in ge2:
print(item)
2.生成器就是函數(shù)體中有yield關(guān)鍵字的函數(shù)
--> (函數(shù)中只要有yield反肋,那么調(diào)用這個(gè)函數(shù)不再是執(zhí)行函數(shù)體并且獲取返回值那伐,而是產(chǎn)生一個(gè)生成器)
通過(guò)next獲取生成器的元素的時(shí)候,會(huì)去執(zhí)行生成器對(duì)應(yīng)的函數(shù)的函數(shù)體,執(zhí)行到y(tǒng)ield為止罕邀,并且將yield后面的值作為返回值(元素值)畅形。
然后保存當(dāng)前結(jié)束的位置,下次一獲取生成器的元素的時(shí)候會(huì)接著上次結(jié)束位置往后執(zhí)行诉探,執(zhí)行到y(tǒng)ield.....
生成器可以當(dāng)成序列來(lái)使用
print('============')
def func1(n):
print('你好日熬,生成器!!')
for x in range(n+1):
print(x)
yield x
print('yeye')
ge3 = func1(3)
print(ge3)
print('=:',next(ge3)) # 0
print('=:',next(ge3)) # 1
print(next(ge3)) # 2
print(next(ge3)) # 3
# print(next(ge3))
def func2():
str1 = 'abcdef'
index = 0
while index < len(str1):
yield str1[index]
index += 1
ge4 = func2()
print(next(ge4))
#
print(next(ge4))
print(list(ge4))
def func3():
num = 0
while True:
yield num
num += 1
ge5 = func3()
print(ge5)
print('==:',next(ge5))
print('==:',next(ge5))
print('========')
for _ in range(5, 100):
print(next(ge5))
print('=======')
print(next(ge5))
練習(xí): 生成器生成的數(shù)據(jù)的規(guī)律:奇數(shù)就返回他本身,偶數(shù)就返回它的2倍
def func2(n):
for x in range(n):
yield x, 2*x, 3*x
# yield 2*x
# yield 3*x
# if x%2:
# yield x
# else:
# yield x*2
g6 = func2(5)
print(next(g6))
print(next(g6))
print(next(g6))
五肾胯、文件的讀寫(xiě)
使用文件可以做數(shù)據(jù)的持久化(本地化) ---> 數(shù)據(jù)庫(kù)文件竖席,txt、json敬肚,plist毕荐,二進(jìn)制文件
1.文件操作 -- 讀寫(xiě)操作
讀 -> 取出文件中的數(shù)據(jù)
寫(xiě) -> 將數(shù)據(jù)寫(xiě)到文件中
所有文件操作的過(guò)程:打開(kāi)文件 --> 操作文件 --> 關(guān)閉文件
2.打開(kāi)文件和關(guān)閉文件
open(file, mode='r',encoding=None)
a. file -> 文件路徑(必須傳參),決定需要打開(kāi)的是哪個(gè)文件
絕對(duì)路徑(不推薦使用)
相對(duì)路徑: ./相對(duì)路徑 (相對(duì)路徑是相對(duì)當(dāng)前py文件對(duì)應(yīng)的文件夾)
./ ---> 當(dāng)前文件夾
../ --> 當(dāng)前文件夾的上層文件夾
.../ --> 當(dāng)前文件夾的上層文件夾的上層文件夾b. mode -> 文件打開(kāi)方式(不同的操作對(duì)應(yīng)不同的打開(kāi)方式)
'r' --> 以只讀的形式打開(kāi)文件, 文本
'rb'/'br' --> 讀操作艳馒,讀出來(lái)的數(shù)據(jù)是二進(jìn)制形式的數(shù)據(jù)
'w' --> 以寫(xiě)的形式打開(kāi)文件
'bw'/'wb' --> 寫(xiě)操作憎亚,將二進(jìn)制數(shù)據(jù)寫(xiě)入文件
'a' --> 寫(xiě)操作,追加c. encoding -> 文本文件的編碼方式
utf-8 :幾乎支持所有的語(yǔ)言文字
gbk : 只支持英文d. open函數(shù)的返回值弄慰,就被打開(kāi)的文件對(duì)象
關(guān)閉文件: 文件對(duì)象.close()
========================文件的讀操作=====================
- 打開(kāi)文件
f1 = open('./test1.txt', 'r', encoding='utf-8')
- 讀文件中的內(nèi)容
文件對(duì)象.read() --> 從文的讀寫(xiě)位置讀到文件結(jié)束,返回讀到的結(jié)果
文件對(duì)象.readline() --> 讀一行
文件對(duì)象.readlines() --> 返回一個(gè)列表第美,列表的元素是文件中每一行的內(nèi)容
content = f1.read()
print(type(content), content)
# print('==:', f1.read())
# content = f1.readlines()
# print(content)
- 關(guān)閉文件
f1.close()
** ==================文件的寫(xiě)操作==================**
- 打開(kāi)文件
'w' -> 將字符串寫(xiě)入文件中, 完全覆蓋文件原來(lái)的內(nèi)容
'wb'/'bw' -> 將二進(jìn)制寫(xiě)入文件中, 完全覆蓋文件原來(lái)的內(nèi)容
'a' -> 追加
f2 = open('./test1.txt', 'w', encoding='utf-8')
- 寫(xiě)入文件
f2.write(content+'hello world') # 這樣寫(xiě)可以接著之前讀取的內(nèi)容寫(xiě)
f2.writelines(['abc\n', '123\n', 'aaaaa\n']) # 覆蓋寫(xiě)
- 關(guān)閉文件
f2.close()