python初學小結三:檔案、集合、函數、變數等,
一、檔案操作:
檔案操作流程:
1、開啟檔案,得到檔案控制代碼並賦值給一個變數
2、通過控制代碼對檔案進行操作
3、關閉檔案
開啟檔案的模式有:
- r,唯讀模式(預設)。
- w,唯寫模式。【不可讀;不存在則建立;存在則刪除內容;】
- a,追加模式。【可讀; 不存在則建立;存在則只追加內容;】
"+" 表示可以同時讀寫某個檔案
- r+,可讀寫檔案。【可讀;可寫;可追加】
- w+,寫讀
- a+,同a
"U"表示在讀取時,可以將 \r \n \r\n自動轉換成 \n (與 r 或 r+ 模式同使用)
"b"表示處理二進位檔案(如:FTP發送上傳ISO鏡像檔案,linux可忽略,windows處理二進位檔案時需標註)
原檔案yesterday2:
(1)讀取檔案
f = open("yesterday2",'r',encoding= "utf-8")#檔案控制代碼,'r'是讀模式,不寫,預設是'r','w'寫是建立一個檔案,原來檔案就沒了
data2 = f.read()
print('------data2------\n',data2)
執行結果:
(2)for迴圈讀取檔案
for i in range(3) :
print(f.readline() )#每次讀一行,一共讀三行
for line in f.readlines() :
print(line.strip()) #strip()把空格與換行去掉
運行前原檔案yesterday2:
執行結果:
(3)寫檔案
f = open("yesterday2",'w',encoding= "utf-8")
f.write("black black heart\n")#'w'寫是建立一個檔案,原來檔案的內容就沒了
f.write("why would you offer more\n")
f.write("Why would you make it easier on me to satisfy")
執行結果:
(4)
f = open("yesterday2",'r',encoding= "utf-8")
print(f.readlines() )#變成每行是一個元素的列表['black black heart\n', 'why would you offer more\n', 'Why would you make it easier on me to satisfy']
(5)
f.readlines()只適合讀小檔案,因為讀時先載入完一次性全讀到記憶體
所以可以使用迴圈,讀一行,刪除一行,記憶體中只儲存一行,就可以處理大檔案了:
count = 0
f = open("yesterday",'r',encoding= "utf-8")
for line in f:
if count ==4:
print('----------我是分割線-------')
count += 1
pass
print(line.strip())
count +=1
f.close()
執行結果:
圖(5)-1
注意:若上述代碼中的“pass”改寫成“continue”,執行結果如下:
圖(5)-2
對比圖(5)-1與圖(5)-2,發現後者少了一句:“If you call your friends and nobody's home. 如果你打電話給朋友卻沒有一人在家 ”,這是因為pass與continue的執行機制不同,當count ==4成立時,pass之後會執行下面的print(line.strip()),而continue之後,程式跳轉到 if count ==4:,所以會少列印一行。
(6)讀寫r+
f = open("yesterday2", 'r+', encoding="utf-8")#讀寫
print(f.readline())
print(f.readline())
print(f.readline())
print(f.tell())
f.write("\n-------add one line-----------\n")#寫在檔案最後
print(f.readline() )
執行結果:
原來檔案變成:
(7)二進位檔案讀rb
f = open("yesterday2", 'rb')#二進位檔案讀
print(f.readline() )
print(f.readline() )
print(f.readline() )
執行結果:
(8)修改檔案
"""修改檔案時,建立立一個檔案,修改好的檔案出現在新檔案中"""
f = open("yesterday2","r",encoding= "utf-8")
f_new = open("yesterday2.bak","w",encoding= "utf-8")
for line in f:
if "經曆了風暴忍受了孤獨" in line:
line = line.replace("經曆了風暴忍受了孤獨","曆經過風雨忍受過孤獨")
f_new.write(line )
f.close()
f_new .close()
執行之後,建立立了一個檔案yesterday2.bak:
(9)With語句:執行完後自動關閉檔案
文法:
with open("yesterday2","r",encoding= "utf-8") as f ,\
open("yesterday2","r",encoding= "utf-8") as f2:
python規範:一行代碼不要超過80個字元,故開啟多個檔案可以用“\”寫成多行
二、進度條小程式:
import sys ,time
for i in range (20):
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(0.1)
三、集合
list_1 = [1,2,5,3,2,6,4,2,6]
list_1 = set (list_1)#把列表變成集合,集合是無序不重複的
list_2 = set([2,5,33,22,1])
print(list_1 ,list_2 )#{1, 2, 3, 4, 5, 6} {33, 2, 1, 5, 22}
print(list_1 ,type(list_1 ))#{1, 2, 3, 4, 5, 6} <class 'set'>
#交集
print(list_1 .intersection(list_2 ))#=print(list_1 & list_2 )#{1, 2, 5}
#並集
print(list_1 .union(list_2) )#=print(list_1 | list_2 )#{1, 2, 3, 4, 5, 6, 33, 22}
#差集
print(list_1 .difference(list_2 ) )#=print(list_1 - list_2 )#{3, 4, 6}
#子集
list_3 = set([1,2,5])
print(list_3 .issubset(list_2 ))#True
#對稱差集,取出兩集合裡面互相都沒有的取出來
print(list_1 .symmetric_difference(list_2 ) )#=list_1^list_2#{33, 3, 4, 22, 6}
list_3 = set([1,2,5])
list_4 = set([4,6,8])
print(list_3 .isdisjoint(list_4 ) )#如果list_3與list_4沒有交集返回True#True
list_1 .add(889)#添加一項
list_1 .update([123,234,345])#添加多項,=list_1 .update({123,234,345})
print(list_1 )#{1, 2, 3, 4, 5, 6, 345, 234, 889, 123}
四、局部變數與全域變數
names = ["Lili","Vae","Cici"]
def change_name():
names[0] = "李立"#列表,集合,字典可以在局部裡面改全域變數的,(元組本來就不可更改,字串,整數不可改)
print("inside func",names)
change_name()
print("outside func", names)
執行結果:
inside func ['李立', 'Vae', 'Cici']
outside func ['李立', 'Vae', 'Cici']
五、一個高階函數的例子
def add(a,b,f):
return f(a)+f(b)
res = add (3,-6,abs) #abs:Return the absolute value of the argument.
print(res ) #9
六、一個遞迴的例子
def calc(n):
print(n)
if int(n / 2) == 0:
return n
return calc(int(n/2))
calc(10) #10 5 2 1
七、
1、函數與過程
#函數
def func1():
"""testing1,這是一個函數"""
print('in the func1')
return 0
#過程,過程就是沒有傳回值的函數
def func2():
'''testing2,這是一個過程'''
print('in the func2')
x = func1()#輸出:in the func1
y = func2()#輸出:in the func1
print('from func1 return is %s'%x)#輸出from func1 return is 0
print('from func1 return is %s'%y)#輸出:from func1 return is None
2、函數調用
import time
def logger():
time_format = '%Y-%m-%d %X'#格式:年月日時分秒
time_current = time .strftime(time_format )# Convert a time tuple to a string according to a format specification.
with open('a.txt','a+') as f:
f.write('%s end action\n'%time_current )
def test1():
print('test1 starting action...')
logger()
test1() #test1 starting action...
同時建立一個檔案a.txt:
3、函數傳回值:
def test1():
print('in the test1')
def test2():
print('in the test2')
return 0
def test3():
print('in the test3')
return 1,'hello',['Bob','lili'],{'name':'Bob'}
y = test2()
z = test3()
print(test1())#None
print(y)#0
print(z)#(1, 'hello', ['Bob', 'lili'], {'name': 'Bob'})當return多於一個返回一個元組
4、函數的預設參數
#預設參數特點:調用函數時,預設參數非必須傳遞
用途:1:def test(x,soft1=True,soft2=True),在預設安裝值時,如果在邏輯判斷時soft1=True,預設安裝soft1
2:串連資料庫:def conn(host,port=3301)
pass
主機指定預設連接埠號碼
(1)
def test(x,y=2):
print(x)
print(y)
test(1,y=3)#1 3
(2)參數組
1def test(*args):
print(args )
test(1,2,3,4,5,4) #(1, 2, 3, 4, 5, 4 )實參不固定時,將接受的實參放到元組
test(*[1,2,3,4,5]) #(1, 2, 3, 4, 5) 即:args=tuple([1,2,3,4,5])
2def test1(x,*args):
print(x)
print(args)
test1(1,2,3,4,5,6,7) # 1 (2,3,4,5,6,7)
3#**kwargs把n個關鍵字參數轉換成字典的方式,key:value,key:value...
def test2(**kwargs ):
print(kwargs )
#print(kwargs['name'])
#print(kwargs['age'])
#print(kwargs['sex'])
test2(name='lili',age=22,sex='Y')#{'name': 'lili', 'age': 22, 'sex': 'Y'}
test2(**{'name':'vae','age':31,'sex':'Y'})#{'name': 'lili', 'age': 22}
分別用4個print輸出結果一次如下:
a{'name': 'lili', 'age': 22, 'sex': 'Y'} {'name': 'vae', 'age': 31, 'sex': 'Y'}
blili vae
c22 31
dY Y
def test3(name,**kwargs ):
print(name)
print(kwargs )
test3('cecila',age=22,sex='Y')
輸出:cecila {'age': 22, 'sex': 'Y'}
# *args:接收N個位置參數,轉換成元組,**kwargs接收關鍵字參數,轉換成字典
def test5(name,age=22,*args,**kwargs ):
print(name)#vae
print(age)#31
print(args)#輸出:()
print(kwargs )#{'sex': 'Y', 'hobby': 'book'}
test5('vae',sex='Y',hobby='book',age=31)