上節課總結
作業總結
1 # isinstance(對象,類名) 判斷變量輸入的對象是否是屬於這個類 2 # 方法1: 3 temp = [11, 22, "", " ", []] 4 print(isinstance(temp, (str, list, tuple))) # 一旦對象屬於這個后面元組的類中的任何一個 就返回true 5 # 方法2: 6 a = type(temp) is list 7 print(a)
2、參數引用
python中 函數傳參,傳引用 ,形參其實是指針映射到 實際參數的的內存地址中的。一旦更改形參對應的值,實際參數也會改。
1、函數傳參數,傳的是個引用,修改 或刪除形參的 值 ,實際參數值也變化
1 def func(args): 2 args.append(123) 3 li=[11,22] 4 func(li) 5 print li 6 7 C:\Python27\python2.exe E:/py/55/learn-python/oldboy/4/test.py 8 [11, 22, 123]
2、形式參數 賦值 另開辟內存
盡管 傳入實際參數 li 使得 args =li ,但是 函數主體 args=123 重新賦值 相當於args重新開辟了一段 內存空間,而原li還是原來的值 如果是同一個變量名 重新賦值,原來占用內存的那個 變量空間 python會定時回收。
1 賦值 盡管 函數調用時候 args=li 但是重新賦值,等於申請了新的內存空間。 2 def func(args): 3 4 args=123 5 6 li=[1,2,3,4] 7 a=func(li) 8 print(li) 9 10 #結果 [1,2,3,4]
1、lambda匿名函數
1 # lambda 匿名函數 2 3 def f1(ar1, ar2): 4 return ar1 + ar2 5 6 7 f2 = lambda ar3, ar4: ar3 + ar4 8 9 ret = f2(3, 4) 10 print(ret)
學習條件運算時,對於簡單的 if else 語句,可以使用三元運算來表示,即:
1 # 普通條件語句 2 if 1 == 1: 3 name = 'wupeiqi' 4 else: 5 name = 'alex' 6 7 # 三元運算 8 name = 'wupeiqi' if 1 == 1 else 'alex'
對於簡單的函數,也存在一種簡便的表示方式,即:lambda表達式
1 # ###################### 普通函數 2 # 定義函數(普通方式) 3 def func(arg): 4 return arg + 1 5 6 # 執行函數 7 result = func(123) 8 9 # ###################### lambda 10 11 # 定義函數(lambda表達式) 12 my_lambda = lambda arg : arg + 1 13 14 # 執行函數 15 result = my_lambda(123)
2、python的內置函數
注:查看詳細猛擊這里
1 大部分函數
abs()返回一個數字的絕對值。如果給出復數,返回值就是該復數的模。
1 >>>print abs(-100) 2 >>>print abs(1+2j) 3 2.2360679775 4 # 內置函數: 5 # 1 abs() 絕對值 6 a = 123 7 b = -123 8 print(abs(a)) 9 print(abs(b))
all()所有為真才為真,只要有一個假就是假
判斷假的條件:任何一種都為假: 0 None 空值(字符串 列表 元組 字典)
1 li = [1, 2, 3, "", False] 2 print(all(li)) 3 ---- 4 C:\Python35\python3.exe E:/py/55/learn-python/oldboy/4/build_in_test.py 5 False
any() 一個為真就為真 同all相反,只有有真就返回True 真: 非0 非None 非空
li = [1, 2, 3, "", False] print(any(li)) ---- C:\Python35\python3.exe E:/py/55/learn-python/oldboy/4/build_in_test.py True
ascii() 用法:ascii(對象) ===去類中找 __repr__ 方法,獲取返回值,2版本中沒有
1 class Foo(object): 2 def __repr__(self): 3 return "hello repr" 4 5 6 li = Foo() 7 n = ascii(li) 8 print(n) 9 10 ---- 11 C:\Python35\python3.exe E:/py/55/learn-python/oldboy/4/build_in_test.py 12 hello repr
bin oct int hex 二進制 八進制 十進制 十六進制
1 # bin() 可以將 八 十 十六 進制 轉換成二進制 2 print(bin(10), bin(0o13), bin(0x14)) 3 # oct() 可以將 二 十 十六 進制 轉換為八進制 4 print(oct(10), oct(0b101), oct(0x14)) 5 # int() 可以將 二 八 十六進制轉換為十進制 6 print(int(0o13), int(0b101), int(0x14)) 7 # hex() 可以將 二 八 十 進制轉換為十六進制 8 print(hex(0b101), hex(110), hex(0o12)) 9 10 11 print(int("0b1011", base=2)) # 必須是字符串,可以不帶o b x .base= 對應的原來進制 12 print(int("72", base=8)) 13 print(int("ac1", base=16))
bool 判斷真假
# 什么是假的。False,0,None,"",[],(),{},用bool值. print(bool(0), bool(None), bool(-1), bool("123"), bool(""))
>>>bool(False) False >>>bool("False") True
看到上面的結果了沒?是True。突然記起Python中除了''、""、0、()、[]、{}、None為False之外,其他的都是True。也就是說上面的'False'就是一個不為空的字符串,所以結果就為True了
將一個值轉化成布爾值,使用標准的真值測試例程。如果x為假或者被忽略它返回False;否則它返回True。bool也是一個類,它是int的子類。bool不能被繼承。它唯一的實例就是False和True。
bytes bytearray 字節列表
byte在前面已經介紹過了 bytes('str',encoding='') bytearray([source[, encoding[, errors]]])
1 返回一個新的字節數組。bytearray類型是一個可變的整數序列,整數范圍為0 <= x < 256(即字節)。 它有可變序列的大多數方法,參見Mutable Sequence Types,同時它也有str類型的大多數方法,參見String Methods。 2 3 source參數可以以不同的方式來初始化數組,它是可選的: 4 5 如果是string,必須指明encoding(以及可選的errors)參數;bytearray()使用str.encode()將字符串轉化為字節數組。 6 如果是integer,生成相應大小的數組,元素初始化為空字節。 7 如果是遵循buffer接口的對象,對象的只讀buffer被用來初始化字節數組。 8 如果是iterable,它的元素必須是整數,其取值范圍為0 <= x < 256,用以初始化字節數組。 9 如果沒有參數,它創建一個大小為0的數組。
chr ord 轉換 ascii對應的字符與十進制整數轉換 可以百度 ascii 對照表
返回一個單字符字符串,字符的ASCII碼為整數i。例如,chr(97)返回字符串'a'。 它是ord()的逆運算。參數的取值范圍為[0..255]的閉區間;如果i超出取值范圍,拋出ValueError。參見unichr()。
1 # chr() 接收一個十進制數字,找到這個數字對應的ASCII碼中對應的字符 2 # ord() 接收一個字符,找到ASCII碼種對應的十進制數字 3 # 一個字節8位,2**8,ASCII碼,256種。驗證碼 4 print(chr(78)) 5 print(ord("A")) 6 7 ---- 8 C:\Python35\python3.exe E:/py/55/learn-python/oldboy/4/build_in_test.py 9 N 10 65
1 #驗證碼 2 import random 3 temp = '' 4 for i in range(4): 5 num = random.randrange(0, 4) # 生成0-4的隨機數 6 if num == 3 or num == 1: # 如果隨機數是1或3,那么在驗證碼中就生成0-9的隨機數 7 rad1 = random.randrange(0, 10) 8 temp += str(rad1) # 字符串轉換拼接 9 else: 10 rad2 = random.randrange(65, 91) # 否則驗證碼中產生字母,范圍是65-90 11 temp += chr(rad2) 12 print(temp)
callable(object) 檢查某個對象是否可以被執行 即 對象(),后面能夠加括號,去執行一段代碼,就是可以執行的
如果object參數可調用,返回True;否則返回False。如果返回真,對其調用仍有可能失敗;但是如果返回假,對object的調用總是失敗。注意類是可調用的(對類調用返回一個新實例);如果類實例有__call__()方法,則它們也是可調用的。
classmethod 后面講 重要
compile 編譯 默認讀文件都是字符串,經過編譯變成代碼
hasattr getattr delattr 反射 后面單獨講
complex 復數
1 創建一個復數,它的值為real + imag*j;或者將一個字符串/數字轉化成一個復數。如果第一個參數是個字符串,它將被解釋成復數,同時函數不能有第二個參數。 2 第二個參數不能是字符串。每個參數必須是數值類型(包括復數)。如果imag被忽略,它的默認值是0,這時該函數就像是int(),long()和float()這樣的數值轉換函數。 3 如果兩個參數都被忽略,返回0j。 4 5 注意 當從字符串轉化成復數的時候,字符串中+或者-兩邊不能有空白。例如,complex('1+2j')是可行的,但complex('1 + 2j')會拋出ValueError異常。 6 在Numeric Types — int, float, long, complex中有對復數的描述。
dir 顯示類的方法
如果沒有參數,返回當前本地作用域內的名字列表。如果有參數,嘗試返回參數所指明對象的合法屬性的列表。
如果對象有__dir__()方法,該方法被調用且必須返回一個屬性列表。這允許實現了定制化的__getattr__()或者__getattribute__()函數的對象定制dir()報告對象屬性的方式。
如果對象沒有提供__dir__(),同時如果對象有定義__dict__屬性,dir()會先嘗試從__dict__屬性中收集信息,然后是對象的類型對象。結果列表沒有必要是完整的,如果對象有定制化的__getattr__(),結果還有可能是不准確的。
對於不同類型的對象,默認的dir()行為也不同,因為它嘗試產生相關的而不是完整的信息:
- 如果對象是模塊對象,列表包含模塊的屬性名。
- 如果對象是類型或者類對象,列表包含類的屬性名,及它的基類的屬性名。
- 否則,列表包含對象的屬性名,它的類的屬性名和類的基類的屬性名。
divmod(10,3) 顯示商和余數
分頁 :余數大於0 商+1 為頁數
在長整數除法中,傳入兩個數字(非復數)作為參數,返回商和余數的二元組。 對於混合的操作數類型,應用二元算術運算符的規則。對於普通整數或者長整數,結果等同於(a // b, a % b)。對於浮點數結果是(q, a % b),q一般是math.floor(a / b),但也可能比那小1。 不管怎樣,q * b + a % b非常接近於a,如果a % b非0,它和b符號相同且0 <= abs(a % b) < abs(b)。
enumerate 序列
enumerate(sequence, start=0)
返回一個枚舉對象。sequence必須是個序列,迭代器iterator,或者支持迭代的對象。enumerate()返回的迭代器的next()方法返回一個元組,它包含一個計數(從start開始,默認為0)和從sequence中迭代得到的值:
1 >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] 2 >>> list(enumerate(seasons)) 3 [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] 4 >>> list(enumerate(seasons, start=1)) 5 [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
等同於:
def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1
eval # 字符串 轉算 執行表達式 有返回值
eval(expression[, globals[, locals]])
參數是Unicode或者Latin-1編碼的字符串,全局變量和局部變量可選。如果有全局變量,globals必須是個字典。如果有局部變量,locals可以是任何映射類型對象。
改變於版本2.4:在此之前locals需要是個字典。
expression參數被當作Python表達式來解析並演算(技術上來說,是個條件列表),使用globals和locals字典作為全局和局部的命名空間。如果globals字典存在,且缺少‘__builtins__’,在expression被解析之前,當前的全局變量被拷貝進globals。這意味着一般來說expression能完全訪問標准__builtin__模塊,且受限的環境會傳播。如果locals字典被忽略,默認是globals字典。如果都被忽略,表達式在eval()被調用的環境中執行。返回值是被演算的表達式的結果。語法錯誤報告成異常。例子:
1 >>> x = 1 2 >>> print eval('x+1') 3 2 4 a = "1 + 3" 5 n = eval(a) 6 print(n) 7 ret = eval("a+60", {"a": 88}) 8 print(ret)
該函數也能執行任意的代碼對象(如compile()返回的結果)。 在這種情況下,傳遞代碼對象而不是字符串。如果代碼對象編譯時mode參數為'exec',eval()返回None。
提示:exec語句支持動態的語句執行。execfile()函數支持執行文件中的語句。globals()和locals()函數返回當前的全局變量和局部變量的字典,可以傳遞給eval()或者execfile()。
參見ast.literal_eval(),該函數能安全演算只含字面量的表達式的字符串。
exec 將字符串 執行 complie 編譯功能 結合是 模板引擎
exec()沒有返回值,只是執行一段Python代碼
exec("for i in range(3):print(i)")
filter map reduce # filter(函數,可迭代的對象)
filter(函數,可迭代的對象)過濾,接收兩個參數,一個是函數,一個是可迭代的對象,迭代每一次都執行這個函數,一旦返回True,把元素放到返回值中,迭代的對象。只有循環的時候能夠直接打印出來
1 def f1(x): 2 if x >22: 3 return True 4 else: 5 return False 6 ret = filter(f1,[11,22,33]) 7 # 默認處理結果返回是一個類,需要迭代打印,因為浪費內存。 可以用next迭代取值。 或者for循環 循環依次取出 8 print(next(ret)) 9 print(list(ret))
1 #filter 實現 2 def myfilter(fuc,seq): 3 new_li = [] 4 for i in seq: 5 #print(i) 6 ret = fuc(i) 7 if ret: 8 new_li.append(i) 9 return new_li 10 def f1(x): 11 if x > 22: 12 return True 13 else: 14 return False 15 li = [11,22,33,44] 16 new=myfilter(f1,li) 17 print(new)
filter(function, iterable)
構造一個列表,列表的元素來自於iterable,對於這些元素function返回真。iterable可以是個序列,支持迭代的容器,或者一個迭代器。如果iterable是個字符串或者元組,則結果也是字符串或者元組;否則結果總是列表。如果function是None,使用特性函數,即為假的iterable被移除。
1 注意,在function不為None的情況下, 2 filter(function, iterable) 3 等同於 4 [item for item in iterable if function(item)]; 5 否則等同於 6 [item foritem in iterable if item](function為None)。
filter中 lambda 函數替換 函數f1
1 ret1 = filter(lambda x:x>22,[11,22,33,44]) 2 print(list(ret1))
1 # map 實現 2 def mymap(fuc,seq): 3 n_li = [] 4 for i in seq: 5 n_i=fuc(i) 6 n_li.append(n_i) 7 # print(n_li) 8 return n_li 9 def f2(x): 10 return x+10 11 li = [11,22,33,44] 12 13 ret = mymap(f2,li) 14 print(ret)
# map(函數,可迭代的對象),批量的操作 def fun2(x): return x + 100
1 def f1(x): 2 if x >22: 3 return True 4 else: 5 return False 6 ret1 = map(f1,[11,22,33,44]) 7 print(list(ret1)) 8 結果是:[False, False, True, True] 9 10 ret1 = map(lambda x:x+22,[11,22,33,44]) 11 print(list(ret1)) 12 結果是:[33, 44, 55, 66]
reduce()函數也是Python內置的一個高階函數。
reduce()函數接收的參數和 map()類似,一個函數 f,一個list,但行為和 map()不同,reduce()傳入的函數 f 必須接收兩個參數,reduce()對list的每個元素反復調用函數f,並返回最終結果值。
例如,編寫一個f函數,接收x和y,返回x和y的和:
1
2
|
def
f(x, y):
return
x
+
y
|
調用 reduce(f, [1, 3, 5, 7, 9])時,reduce函數將做如下計算:
1
2
3
4
5
|
先計算頭兩個元素:f(
1
,
3
),結果為
4
;
再把結果和第
3
個元素計算:f(
4
,
5
),結果為
9
;
再把結果和第
4
個元素計算:f(
9
,
7
),結果為
16
;
再把結果和第
5
個元素計算:f(
16
,
9
),結果為
25
;
由於沒有更多的元素了,計算結束,返回結果
25
。
|
上述計算實際上是對 list 的所有元素求和。雖然Python內置了求和函數sum(),但是,利用reduce()求和也很簡單。
reduce()還可以接收第3個可選參數,作為計算的初始值。如果把初始值設為100,計算:
1
|
reduce
(f, [
1
,
3
,
5
,
7
,
9
],
100
)
|
結果將變為125,因為第一輪計算是:
計算初始值和第一個元素:f(100, 1),結果為101。
判斷對象是否是某個類創建的 父類的話也成立
issubclass 是否是子類 后面講
iter 迭代器 后面講
obj = iter([11,22,33,44]) ret = next(obj) print(ret)
yield 生成器,后面講
max 最大 min
li = [11,22,33,44]
max(li)
pow求次方
a= pow(2,10) print(a)
repr() === ascii()
round 四舍五入
round()方法返回 x 的小數點四舍五入到n個數字
1 語法 2 以下是round()方法的語法: 3 4 round( x [, n] ) 5 參數 6 x --這是一個數值表達式 7 8 n --這也是一個數值表達式 9 10 返回值 11 該方法返回 x 的小數點四舍五入到n個數字 12 13 例子 14 下面的例子顯示了round()方法的使用 15 16 #!/usr/bin/python 17 18 print "round(80.23456, 2) : ", round(80.23456, 2) 19 print "round(100.000056, 3) : ", round(100.000056, 3) 20 print "round(-100.000056, 3) : ", round(-100.000056, 3) 21 當我們運行上面的程序,它會產生以下結果: 22 23 round(80.23456, 2) : 80.23 24 round(100.000056, 3) : 100.0 25 round(-100.000056, 3) : -100.0
slice 對象切片
在python中,list, tuple以及字符串等可以遍歷訪問的類型都可以應用slice訪問。slice本身的意思是指切片,在這些可以遍歷訪問的類型中截取其中的某些部分。
sum 求和
sum(iterable[, start])
將start以及iterable的元素從左向右相加並返回總和。start默認為0。iterable的元素通常是數字,start值不允許是一個字符串。
對於某些使用場景,有比sum()更好的選擇。連接字符串序列的首選和快速的方式是調用''.join(sequence)。如要相加擴展精度的浮點數,請參閱math.fsum()。若要連接一系列的可迭代量,可以考慮使用itertools.chain()。
其實sum()的參數是一個list 例如: sum([1,2,3]) sum(range(1,11)) 還有一個比較有意思的用法 a = range(1,11) b = range(1,10) c = sum([item for item in a if item in b]) print c 輸出:
supper 找到父類
super
(
type[, object-or-type])
返回一個代理對象,這個對象指派方法給一個父類或者同類. 這對進入類中被覆蓋的繼承方法非常有用。搜索順序和 getattr() 一樣。而它自己的 類型則被忽略
vars 對象的變量個數
zip 拉鏈 將兩個列表合起來,做成一個列表,元素為數組
1 >>> a = range(5,10) 2 >>> a 3 [5, 6, 7, 8, 9] 4 >>> b =(1,5) 5 >>> b 6 (1, 5) 7 >>> b =range(1,5) 8 >>> b 9 [1, 2, 3, 4] 10 >>> b.append(0) 11 >>> b 12 [1, 2, 3, 4, 0] 13 >>> zip(a,b) 14 [(5, 1), (6, 2), (7, 3), (8, 4), (9, 0)] 15 >>> b.pop() 16 >>> b 17 [1, 2, 3, 4] 18 >>> a 19 [5, 6, 7, 8, 9] 20 >>> zip(a,b) 21 [(5, 1), (6, 2), (7, 3), (8, 4)]
sort 函數
sorted(iterable[, cmp[, key[, reverse]]])
依據iterable中的元素返回一個新的列表。
可選參數cmp、key和reverse與list.sort()方法的參數含義相同(在可變的序列類型一節描述)。
cmp指定一個自定義的帶有兩個參數的比較函數(可迭代的元素),它應該根據第一個參數是小於、等於還是大於第二個參數返回負數、零或者正數:cmp=lambda x,y: cmp(x.lower(), y.lower())。默認值是None。
key指定一個帶有一個參數的函數,它用於從每個列表元素選擇一個比較的關鍵字:key=str.lower。默認值是None(直接比較元素)。
reverse是一個布爾值。如果設置為True,那么列表元素以反向比較排序。
通常情況下,key和reverse轉換處理比指定一個等同的cmp函數要快得多。這是因為cmp為每個元素調用多次但是key和reverse只會觸摸每個元素一次。使用functools.cmp_to_key()來轉換舊式的cmp函數為key函數。
關於排序的實例和排序的簡明教程,請參閱Sorting HowTo。
1 >>> sorted([5, 2, 3, 1, 4]) 2 [1, 2, 3, 4, 5] 3 4 >>> a = [5, 2, 3, 1, 4] 5 >>> a.sort() 6 >>> a 7 [1, 2, 3, 4, 5] 8 9 sorted 默認值對列表排序故字典只對key排序 10 >>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) 11 [1, 2, 3, 4, 5] 12 13 key 函數 14 >>> sorted("This is a test string from Andrew".split(), key=str.lower) 15 ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This'] 16 17 lambda 18 >>> student_tuples = [ 19 ('john', 'A', 15), 20 ('jane', 'B', 12), 21 ('dave', 'B', 10), 22 ] 23 >>> sorted(student_tuples, key=lambda student: student[2]) # sort by age 24 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] 25 26 The same technique works for objects with named attributes. For example: 27 28 >>> class Student: 29 def __init__(self, name, grade, age): 30 self.name = name 31 self.grade = grade 32 self.age = age 33 def __repr__(self): 34 return repr((self.name, self.grade, self.age)) 35 def weighted_grade(self): 36 return 'CBA'.index(self.grade) / float(self.age) 37 38 >>> student_objects = [ 39 Student('john', 'A', 15), 40 Student('jane', 'B', 12), 41 Student('dave', 'B', 10), 42 ] 43 >>> sorted(student_objects, key=lambda student: student.age) # sort by age 44 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] 45 46 更多詳見 https://wiki.python.org/moin/HowTo/Sorting/
重點掌握的
3、open() 函數 處理文件
open函數,該函數用於文件處理
操作文件時,一般需要經歷如下步驟:
- 打開文件
- 操作文件
- 關閉文件
而實際工作操作的時候忘了關閉文件,所以我們用另一種操作,用with語句來操作,這樣就不需要手動來關閉文件。在后面的操作中,都會以with方式來打開文件。
一、打開文件
文件句柄 = open('文件路徑', '模式')
打開文件時,需要指定文件路徑和以何等方式打開文件,打開后,即可獲取該文件句柄,日后通過此文件句柄對該文件操作。
1 #windows下默認為gbk,要指定編碼為'utf-8' 2 #'r'為只讀,'1.txt'為文件路徑 3 f=open('1.txt','r',encoding='utf-8') #打開文件 4 data=f.read() #操作文件 5 f.close() #關閉文件 6 print(data) 7 8 # 用with語句打開,不需要自動關閉 9 with open('1.txt','r',encoding='utf-8') as f: 10 print(f.read())
打開文件的模式有:
- r ,只讀模式【默認】
- w,只寫模式【不可讀;不存在則創建;存在則清空內容;】
- x, 只寫模式【不可讀;不存在則創建,存在則報錯】
- a, 追加模式【不可讀; 不存在則創建;存在則只追加內容;】
"+" 表示可以同時讀寫某個文件
- r+, 讀寫【可讀,可寫】
- w+,寫讀【可讀,可寫】
- x+ ,寫讀【可讀,可寫】
- a+, 寫讀【可讀,可寫】
"b"表示以字節的方式操作
- rb 或 r+b
- wb 或 w+b
- xb 或 w+b
- ab 或 a+b
注:以b方式打開時,讀取到的內容是字節類型,寫入時也需要提供字節類型
1 文件 hello.txt 2 Hello Word! 3 abc 4 abc 5 abc 6 漢字 7 8 代碼 : 9 f = open("hello.txt",'rb') # 用到b模式的時候 就不能跟 編碼了。 10 data = f.read() 11 f.close() 12 print(data) 13 14 輸出 15 C:\Python35\python3.exe E:/py_test/s5/open.py 16 b'Hello Word!\r\n123\r\nabc\r\n456\r\nabc\r\n789\r\nabc\r\n\xe5\x88\x98\xe5\xbb\xba\xe4\xbd\x90'
python open函數 r 和rb區別
下面着重講解下用"+" 同時讀寫某個文件的操作
1 # r+形式 寫的時候,如果直接寫,在寫之前沒有讀取過就是直接從前面開始寫進去,tell指針位置是你寫之后的位置,再次讀取也是從這個位置開始讀,如果有讀過,不管事read 還是readline 還是read(1)都是在末尾追加,指針移到到最后。
但是讀的話還是從之前讀之后的tell位置繼續讀。
2 # 大家一定要清楚的明白讀寫的時候指針指向的位置,下面的這個例子一定要懂 3 # f.tell() 讀取指針的位置 4 # f.seek(0) 設置指針的位置 5 with open('1.txt','r+',encoding='utf-8') as f: 6 print(f.tell()) #打印下 文件開始時候指針指向哪里 這里指向 0 7 print(f.read()) #讀出文件內容'字符串',讀了幾個指針到什么位置,read是全部讀完了。 8 print(f.tell()) #文件指針位置,讀了幾個位置,就在哪個位置,如果read()了,那就在最后,如果read(1) tell 就是1 9 f.write('科比') #寫入內容'科比',需要特別注意,如果沒有讀全部,或者沒有讀過,直接寫入的話是從指針為0的位置開始寫入,原先有內容的話會覆蓋原來的內容,如果讀取過,那么不管指針在哪都是追加到最后的。並且指針tell也在最后 10 print(f.read()) #寫完之后再次去讀的時候,需要特別注意的是,讀的位置,是你之前讀之后的位置,而不是寫完之后tell的位置 11 print(f.tell()) #指針指到15 12 f.seek(0) #將指針內容指到 0 位置,移動指針的時候,要注意漢字連續字節不能被拆分開,不然報錯,
13 print(f.read()) #因為文件指針指到開頭去了,所以可以讀到內容 字符串科比 14 15 # w+形式 存在的話先清空 一寫的時候指針到最后 16 with open('1.txt','w+') as f: 17 f.write('Kg') #1.txt存在,所以將內面的內容清空,然后再寫入 'kg' 18 print(f.tell()) #此時指針指向2 19 print(f.read()) #讀不到內容,因為指針指向末尾了 20 f.seek(0) 21 print(f.read()) #讀到內容,因為指針上一步已經恢復到起始位置 22 23 # a+打開的時候指針已經移到最后,寫的時候不管怎樣都往文件末尾追加,這里就不再演示了,讀者可以自己試一下 24 # x+文件存在的話則報錯,也不演示了
Python文件讀取方式
二、操作

1 class file(object) 2 def close(self): # real signature unknown; restored from __doc__ 3 關閉文件 4 """ 5 close() -> None or (perhaps) an integer. Close the file. 6 7 Sets data attribute .closed to True. A closed file cannot be used for 8 further I/O operations. close() may be called more than once without 9 error. Some kinds of file objects (for example, opened by popen()) 10 may return an exit status upon closing. 11 """ 12 13 def fileno(self): # real signature unknown; restored from __doc__ 14 文件描述符 15 """ 16 fileno() -> integer "file descriptor". 17 18 This is needed for lower-level file interfaces, such os.read(). 19 """ 20 return 0 21 22 def flush(self): # real signature unknown; restored from __doc__ 23 刷新文件內部緩沖區,將內存中寫入的內容刷進硬盤。 24 """ flush() -> None. Flush the internal I/O buffer. """ 25 pass 26 27 28 def isatty(self): # real signature unknown; restored from __doc__ 29 判斷文件是否是同意tty設備 30 """ isatty() -> true or false. True if the file is connected to a tty device. """ 31 return False 32 33 34 def next(self): # real signature unknown; restored from __doc__ 35 獲取下一行數據,不存在,則報錯 36 """ x.next() -> the next value, or raise StopIteration """ 37 pass 38 39 def read(self, size=None): # real signature unknown; restored from __doc__ 40 讀取指定字節數據,默認讀取全部,漢字的話讀取按照字符來讀。 41 """ 42 read([size]) -> read at most size bytes, returned as a string. 43 44 If the size argument is negative or omitted, read until EOF is reached. 45 Notice that when in non-blocking mode, less data than what was requested 46 may be returned, even if no size parameter was given. 47 """ 48 pass 49 50 def readinto(self): # real signature unknown; restored from __doc__ 51 讀取到緩沖區,不要用,將被遺棄 52 """ readinto() -> Undocumented. Don't use this; it may go away. """ 53 pass 54 55 def readline(self, size=None): # real signature unknown; restored from __doc__ 56 僅讀取一行數據 57 """ 58 readline([size]) -> next line from the file, as a string. 59 60 Retain newline. A non-negative size argument limits the maximum 61 number of bytes to return (an incomplete line may be returned then). 62 Return an empty string at EOF. 63 """ 64 pass 65 66 def readlines(self, size=None): # real signature unknown; restored from __doc__ 67 讀取所有數據,並根據換行保存值列表 68 """ 69 readlines([size]) -> list of strings, each a line from the file. 70 71 Call readline() repeatedly and return a list of the lines so read. 72 The optional size argument, if given, is an approximate bound on the 73 total number of bytes in the lines returned. 74 """ 75 return [] 76 77 def seek(self, offset, whence=None): # real signature unknown; restored from __doc__ 78 指定文件中指針位置 79 """ 80 seek(offset[, whence]) -> None. Move to new file position. 81 82 Argument offset is a byte count. Optional argument whence defaults to 83 (offset from start of file, offset should be >= 0); other values are 1 84 (move relative to current position, positive or negative), and 2 (move 85 relative to end of file, usually negative, although many platforms allow 86 seeking beyond the end of a file). If the file is opened in text mode, 87 only offsets returned by tell() are legal. Use of other offsets causes 88 undefined behavior. 89 Note that not all file objects are seekable. 90 """ 91 pass 92 93 def tell(self): # real signature unknown; restored from __doc__ 94 獲取當前指針位置 95 """ tell() -> current file position, an integer (may be a long integer). """ 96 pass 97 98 def truncate(self, size=None): # real signature unknown; restored from __doc__ 99 截斷數據,僅保留指定之前數據,指針所在位置之前的內容 100 """ 101 truncate([size]) -> None. Truncate the file to at most size bytes. 102 103 Size defaults to the current file position, as returned by tell(). 104 """ 105 pass 106 107 def write(self, p_str): # real signature unknown; restored from __doc__ 108 寫內容 109 """ 110 write(str) -> None. Write string str to file. 111 112 Note that due to buffering, flush() or close() may be needed before 113 the file on disk reflects the data written. 114 """ 115 pass 116 117 def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__ 118 將一個字符串列表寫入文件 119 """ 120 writelines(sequence_of_strings) -> None. Write the strings to the file. 121 122 Note that newlines are not added. The sequence can be any iterable object 123 producing strings. This is equivalent to calling write() for each string. 124 """ 125 pass 126 127 def xreadlines(self): # real signature unknown; restored from __doc__ 128 可用於逐行讀取文件,非全部 129 """ 130 xreadlines() -> returns self. 131 132 For backward compatibility. File objects now include the performance 133 optimizations previously implemented in the xreadlines module. 134 """ 135 pass 136 137 2.x 138 139 2.x Code

1 class TextIOWrapper(_TextIOBase): 2 """ 3 Character and line based layer over a BufferedIOBase object, buffer. 4 5 encoding gives the name of the encoding that the stream will be 6 decoded or encoded with. It defaults to locale.getpreferredencoding(False). 7 8 errors determines the strictness of encoding and decoding (see 9 help(codecs.Codec) or the documentation for codecs.register) and 10 defaults to "strict". 11 12 newline controls how line endings are handled. It can be None, '', 13 '\n', '\r', and '\r\n'. It works as follows: 14 15 * On input, if newline is None, universal newlines mode is 16 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and 17 these are translated into '\n' before being returned to the 18 caller. If it is '', universal newline mode is enabled, but line 19 endings are returned to the caller untranslated. If it has any of 20 the other legal values, input lines are only terminated by the given 21 string, and the line ending is returned to the caller untranslated. 22 23 * On output, if newline is None, any '\n' characters written are 24 translated to the system default line separator, os.linesep. If 25 newline is '' or '\n', no translation takes place. If newline is any 26 of the other legal values, any '\n' characters written are translated 27 to the given string. 28 29 If line_buffering is True, a call to flush is implied when a call to 30 write contains a newline character. 31 """ 32 def close(self, *args, **kwargs): # real signature unknown 33 關閉文件 34 pass 35 36 def fileno(self, *args, **kwargs): # real signature unknown 37 文件描述符 38 pass 39 40 def flush(self, *args, **kwargs): # real signature unknown 41 刷新文件內部緩沖區 42 pass 43 44 def isatty(self, *args, **kwargs): # real signature unknown 45 判斷文件是否是同意tty設備 46 pass 47 48 def read(self, *args, **kwargs): # real signature unknown 49 讀取指定字節數據 50 pass 51 52 def readable(self, *args, **kwargs): # real signature unknown 53 是否可讀 54 pass 55 56 def readline(self, *args, **kwargs): # real signature unknown 57 僅讀取一行數據 58 pass 59 60 def seek(self, *args, **kwargs): # real signature unknown 61 指定文件中指針位置 62 pass 63 64 def seekable(self, *args, **kwargs): # real signature unknown 65 指針是否可操作 66 pass 67 68 def tell(self, *args, **kwargs): # real signature unknown 69 獲取指針位置 70 pass 71 72 def truncate(self, *args, **kwargs): # real signature unknown 73 截斷數據,僅保留指定之前數據 74 pass 75 76 def writable(self, *args, **kwargs): # real signature unknown 77 是否可寫 78 pass 79 80 def write(self, *args, **kwargs): # real signature unknown 81 寫內容 82 pass 83 84 def __getstate__(self, *args, **kwargs): # real signature unknown 85 pass 86 87 def __init__(self, *args, **kwargs): # real signature unknown 88 pass 89 90 @staticmethod # known case of __new__ 91 def __new__(*args, **kwargs): # real signature unknown 92 """ Create and return a new object. See help(type) for accurate signature. """ 93 pass 94 95 def __next__(self, *args, **kwargs): # real signature unknown 96 """ Implement next(self). """ 97 pass 98 99 def __repr__(self, *args, **kwargs): # real signature unknown 100 """ Return repr(self). """ 101 pass 102 103 buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 104 105 closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 106 107 encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 108 109 errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 110 111 line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 112 113 name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 114 115 newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 116 117 _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 118 119 _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 120 121 3.x 122 123 3.x
操作示例:
測試的文件名是 "hello.txt" ,文件內容為:
1 Hello Word! 2 abc 3 abc 4 abc
read 方法
1 # 以只讀的方式打開文件hello.txt 2 f = open("hello.txt","r") 3 # 讀取文件內容賦值給變量c 4 c = f.read() 5 # 關閉文件 6 f.close() 7 # 輸出c的值 8 print(c) 9 10 輸出結果 11 C:\Python35\python3.exe E:/py_test/s5/open.py 12 Hello Word! 13 abc 14 abc 15 abc
readline
1 # 以只讀模式打開文件hello.txt 2 f = open("hello.txt","r") 3 # 讀取第一行 strip 去除空行 4 c1 = f.readline().strip() 5 # 讀取第二行 6 c2 = f.readline().strip() 7 # 讀取第三行 8 c3 = f.readline().strip() 9 # 關閉文件 10 f.close() 11 # 輸出讀取文件第一行內容 12 print(c1) 13 # 輸出讀取文件第二行內容 14 print(c2) 15 # 輸出讀取文件第三行內容 16 print(c3) 17 18 C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py 19 Hello Word! 20 123 21 abc
readlines 獲取到的是列表,每行是列表的元素
1 # 以只讀的方式打開文件hello.txt 2 f = open("hello.txt","r") 3 # 將文件所有內容賦值給c 4 c = f.readlines() 5 # 查看數據類型 6 print(type(c)) 7 # 關閉文件 8 f.close() 9 # 遍歷輸出文件內容 # n.strip()去除空行 10 for n in c: 11 print(n.strip()) 12 13 C:\Python35\python3.exe E:/py/55/learn-python/oldboy/4/test_file.py 14 <class 'list'> 15 Hello Word! 16 abc 17 abc 18 abc
Python文件寫入方式
write
1 # 以只寫的模式打開文件write.txt,沒有則創建,有則覆蓋內容 2 file = open("write.txt","w") 3 # 在文件內容中寫入字符串test write 4 file.write("test write") 5 # 關閉文件 6 file.close()
writeline
# 以只寫模式打開一個不存在的文件wr_lines.txt f = open("wr_lines.txt","w",encoding="utf-8") # 寫入一個列表 f.writelines(["11","22","33"]) # 關閉文件 f.close()
wr_lines.txt 文件內容:
Python文件操作所提供的方法
close(self):
關閉已經打開的文件
f.close()
fileno(self):
文件描述符
1 f = open("hello.txt",'rb') 2 data = f.fileno() 3 f.close() 4 print(data)
輸出結果
C:\Python35\python3.exe E:/py_test/s5/open.py
3
flush(self):
刷新緩沖區的內容到硬盤中
f.flush() #在r+ 或者 rb+模式下還沒有 f.close() 或者之后,flush方法 就會將內存的數據寫入硬盤。 否則在其他地方調用這個文件的新內容會找不到
isatty(self):
判斷文件是否是tty設備,如果是tty設備則返回 True ,否則返回 False
f = open("hello.txt","r") ret = f.isatty() f.close() print(ret) C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py False
readable(self):
是否可讀,如果可讀返回 True ,否則返回 False
1 f = open("hello.txt","r") 2 ret = f.readable() 3 f.close() 4 print(ret) 5 6 C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py 7 True
readline(self, limit=1):
每次僅讀取一行數據
f = open("hello.txt","r") print(f.readline()) print(f.readline()) f.close() C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py Hello Word! 123
readlines(self, hint=1):
把每一行內容當作列表中的一個元素
f = open("hello.txt","r") print(f.readlines()) f.close() C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py ['Hello Word!\n', '123\n', 'abc\n', '456\n', 'abc\n', '789\n', 'ab c']
tell(self):
獲取指針位置
1 f = open("hello.txt","r") 2 print(f.tell()) 3 f.close() 4 5 C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py 6 0
seek(self, offset, whence=io.SEEK_SET):
指定文件中指針位置
f = open("hello.txt","r") print(f.tell()) f.seek(3) print(f.tell()) f.close() C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py 0 3
seekable(self):
指針是否可操作
1 f = open("hello.txt","r") 2 print(f.seekable()) 3 f.close() 4 5 C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py 6 True
writable(self):
是否可寫
1 f = open("hello.txt","r") 2 print(f.writable()) #只讀模式不可讀 3 f.close() 4 5 C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py 6 False
writelines(self, lines):
寫入文件的字符串序列,序列可以是任何迭代的對象字符串生產,通常是一個 字符串列表 。
1 f = open("wr_lines.txt","w") 2 f.writelines(["11","22","33"]) 3 f.close() 4 5 寫入結果 6 112233
read(self, n=None):
讀取指定字節數據,后面不加參數默認讀取全部
f = open("wr_lines.txt","r") print(f.read(3)) f.seek(0) print(f.read()) f.close() C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py 112 112233
write(self, s):
往文件里面寫內容
1 f = open("wr_lines.txt","w") 2 f.write("abcabcabc") 3 f.close() 4 5 文件內容 6 abcabcabc
一行一行的讀文件 for in
f=open("test.txt","r") for line in f: print(line) #一行一行將文件讀出來
假設現在有這樣一個需求,有一個10G大的文件,如何拷貝到另一個文件中去?下面將講一下如何同時打開兩個文件進行處理,以及文件太大的時候如何讀取用with語句就可以同時打開兩個文件,一個讀,一個寫。假設1.txt文件有10G大,如果用read則一次性就將內容讀到內存中去了,這顯然不合適,如果用readline()的話雖然也可以讀一行,但是並不知道何時結束,但是可以用for循環讀取文件這個可迭代的對象,一行行的讀取。下面三行代碼就可以實現了
1 with open('1.txt','r',encoding='utf-8') as fread,open('2.txt','w') as fwrite: 2 for line in fread: #一行行的讀 3 fwrite.write(line) #一行行的寫
三、管理上下文
為了避免打開文件后忘記關閉,可以通過管理上下文,即:
with open('log','r') as f: ...
如此方式,當with代碼塊執行完畢時,內部會自動關閉並釋放文件資源。
在Python 2.7 及以后,with又支持同時對多個文件的上下文進行管理,即:
with open('log1') as obj1, open('log2') as obj2: pass
open fileinput 練習 更改文本內容 增刪改查用戶 以及注冊登陸
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 def login(username, password): 4 """ 5 判斷用戶名,密碼是否正確 6 :param username: 用戶名 7 :param password: 密碼 8 :return: True:正確登陸,False:用戶名或密碼錯誤,無法登陸 9 """ 10 with open("db", "r", encoding="utf-8") as f: 11 for line in f: 12 line_list = line.strip().split(":") 13 if username == line_list[0] and password == line_list[1]: 14 return True 15 return False 16 17 def register(): 18 """ 19 新用戶注冊判斷用戶名是否存在,密碼位數是否正確 20 :return: True:注冊成功 21 """ 22 user = input("請輸入用戶名:") 23 while True: 24 ret = user_exist(user) # 判斷用戶名是否存在 25 if ret: 26 print("用戶名已存在!") 27 user = input("請重新輸入用戶名:") 28 continue 29 else: 30 break 31 pwd = pwd_rule() # 密碼規則驗證及獲取輸入密碼 32 with open("db", "a") as f: 33 if f.tell() != 0: 34 temp = "\n" + user + ":" + pwd 35 f.write(temp) 36 return True 37 else: 38 temp = user + ":" + pwd 39 f.write(temp) 40 return True 41 42 def user_exist(username): 43 ''' 44 驗證密碼用戶名是否重復 45 :param username: 用戶名 46 :return: True:用戶名重復 47 ''' 48 with open("db", "r", encoding="utf-8") as f: 49 for line in f: 50 line_list = line.strip().split(":") 51 if username == line_list[0]: 52 return True 53 return False 54 55 def change_pwd(username, password): 56 """ 57 修改密碼 58 :param username: 原始賬戶 59 :param password: 原始密碼 60 :return: True:修改成功。 61 """ 62 with open("db", "r", encoding="utf-8") as f: 63 data = f.readlines() 64 # print(data) 65 for i in range(len(data)): 66 line_list = data[i].strip().split(":") 67 if username == line_list[0] and password == line_list[1]: # 判定賬戶輸入正確 68 print("驗證成功,開始設定新密碼\n") 69 new_pwd = pwd_rule() 70 print(new_pwd) 71 data[i] = username + ":" + new_pwd + "\n" # 設定新密碼行 72 with open("db", "w", encoding="utf-8") as n: 73 n.writelines(data) # 重新寫進去 74 return True 75 print("驗證失敗") 76 return False 77 78 def del_user(username, password): 79 with open("db", "r", encoding="utf-8") as f: 80 data = f.readlines() 81 # print(data) 82 for i in range(len(data)): 83 line_list = data[i].strip().split(":") 84 if username == line_list[0] and password == line_list[1]: # 判定賬戶輸入正確 85 print("驗證成功,確定刪除用戶\n") 86 inp = input("y/s?") 87 if inp == "y": 88 del data[i] 89 with open("db", "w", encoding="utf-8") as n: 90 n.writelines(data) # 重新寫進去 91 print("刪除成功") 92 return True 93 else: 94 print("取消刪除") 95 return True 96 97 print("驗證失敗") 98 return False 99 100 def pwd_rule(): 101 """ 102 新密碼的輸入,判定密碼規則是否符合 103 :return: 返回密碼 104 """ 105 while True: 106 password = input("請輸入密碼:") 107 if len(password) < 6: # 密碼少於6位需要重新輸入 108 print("密碼至少6位") 109 # password = input("重新輸入密碼:") 110 continue 111 pwd_again = input("請再次輸入:") # 密碼2次確認。2次輸入錯誤重新輸入。 112 if password == pwd_again: 113 return password 114 else: 115 print("兩次輸入不一樣") 116 continue 117 118 def confirm(chose): 119 """ 120 操作選項 121 :param chose: 選項 122 :return: 無 123 """ 124 while True: 125 if chose == 1: 126 flag = False 127 while True: 128 user = input("請輸入用戶名:") 129 pwd = input("請輸入密碼:") 130 ret = login(user, pwd) 131 if ret: 132 print("登陸成功") 133 flag = True 134 break 135 else: 136 print("登陸失敗,重新登陸") 137 continue 138 if flag: 139 break 140 elif chose == 2: 141 ret = register() 142 if ret: 143 print("注冊成功") 144 break 145 146 elif chose == 3: 147 user = input("請輸入用戶名:") 148 pwd = input("請輸入密碼:") 149 if change_pwd(user, pwd): 150 print("密碼修改成功") 151 break 152 elif chose == 4: 153 user = input("請輸入用戶名:") 154 pwd = input("請輸入密碼:") 155 if del_user(user, pwd): 156 print("操作完成") 157 break 158 elif chose == 5: 159 print("退出") 160 break 161 else: 162 new_chose = int(input("輸入錯誤,重新選擇:\n")) 163 chose = new_chose 164 continue 165 166 def main(): 167 print("歡迎登陸SB系統!") 168 print("請選擇:\n1、登陸\n2、注冊\n3、修改密碼\n4、刪除用戶\n5、退出") 169 inp = int(input()) 170 confirm(inp) 171 172 if __name__ == "__main__": 173 main()