文件的基本操做python
open()程序員
用於文件處理app
操做文件時,通常須要經歷以下步驟:less
基本操做文件方式ide
open(文件名/路徑,模式,編碼),默認模式爲「只讀」函數
f = open('test.log', "r") data = f.read() f.close() print(data) >>> testlog
打開文件時,須要指定文件路徑和以何等方式打開文件,打開後,便可獲取該文件句柄,往後經過此文件句柄對該文件操做。ui
打開文件的模式: this
f = open('test.log') data = f.read() f.close() print(data) >>> abc123
f = open('test.log', 'w') data = f.write('defg123456') #以寫方式覆蓋文件 f.close() print(data) >>> 10 #寫入10個字符
f = open('test.log', 'w') data = f.read() f.close() print(data) >>> data = f.read() io.UnsupportedOperation: not readable#只寫方式不能讀取文件內同
f = open('test2.log', 'x')#文件不存在,建立一個新的文件 f.write("qwe456") f.close() f = open('test2.log', 'x') f.write("zxcv123456") f.close() >>> f = open('test2.log', 'x') FileExistsError: [Errno 17] File exists: 'test2.log'#文件已經存在,不能建立同名文件
f = open('test2.log', 'a') data = f.write("9876543210") f.close() print(data) >>> 10 #寫入10個字符
"+" 表示能夠同時讀寫某個文件編碼
先讀取文檔,在文檔末尾追加寫入,指針移到最後spa
f = open("test.log", 'r+', encoding = "utf-8") print(f.tell()) #顯示指針位置,指針從開始向後讀取 f.write("123456") data = f.read() print(data) print(f.tell()) #讀取文件後指針位置 f.close() >>> 0 123456 6
先把文件內容清空,從開始向後讀取文件;從新寫入內容後,指針移到最後,讀取文件。
f = open("test.log", 'w+', encoding = "utf-8") f.write("123456")#寫入完成後,文檔指針位置在文件末尾 f.seek(0)#設定指針在文檔開始 data = f.read() print(data)
若文件存在,系統報錯,建新文件,再寫入內容後,指針移到最後,讀取文件。
文件打開同時,文檔指針已經設定在最後, 寫入文件後,指針留在文件的最後。
f = open("test.log", 'a+', encodig"utf-8") f.write("987654") print(f.tell()) #顯示指針位置 f.seek(0) #設定指針爲文檔最開始 data = f.read() print(data) >>> 6 987654
r+ w+ x+ a+都以指針位置讀取或寫入數據。
"b"表示以字節(bytes)的方式操做
f = open('test2.log', 'wb') f.write(bytes("中國", encoding='utf-8')) f.close() f = open('test2.log', "rb") data = f.read() f.close() print(data) str_data = str(data, encoding='utf - 8') print(str_data) >>> b'\xe4\xb8\xad\xe5\x9b\xbd' 中國
f = open('test2.log', 'wb') str_data = "中國" bytes_data = bytes(str_data, encoding = 'utf-8')#指定寫如的編碼 f.write(bytes_data) f.close()
f = open('test2.log', 'wb') f.write("中國") f.close() >>> f.write("中國") TypeError: a bytes-like object is required, not 'str'
注:以b方式打開時,讀取到的內容是字節類型,寫入時也須要提供字節類型
普通打開方式
python內部將底層010101010的字節 轉換成 字符串
二進制打開方式
python將讀取將底層010101010的字節 再按照程序員設定的編碼,轉換成字符串。
f = open('test2.log', 'wb') f.write(bytes("中國", encoding='utf-8')) f.close() f = open('test2.log', "rb") data = f.read() f.close() print(data) str_data = str(data, encoding='utf - 8') print(str_data) >>> b'\xe4\xb8\xad\xe5\x9b\xbd' 中國
文件操做內部函數
f.flush()
主動把內容刷新到硬盤內
f = open("test.log", "r+", encoding="utf-8") f.write("123456789")#內容寫入到內存中 f.flush()#把內容刷新到硬盤內 i = input(">>>")
f.readline()
僅讀取一行內容
f1 = open("test.log", 'r+', encoding = 'utf-8') d = f1.realline() f.close() print(d)
f.tell()
顯示指針位置
f.seek()
設定指針位置
f.trucate()
截取數據,僅保留指針前的數據
f = open("test.log", "r+", encoding = "utf-8") print(f.tell()) print(f.seek(6)) f.truncate() f1.close()
f.close()
關閉文件,把文件保存在硬盤中
使用for循環讀取文件
f = open("xxx", "r")
for line in f: print(line)
with 循環打開文件
with open("xxx", 'r') as f: f.read() f = open("xxx", 'r') f.read() #不須要f.close()關閉文件
with支持同時打開兩個文件,從源文件中逐行拷貝到目標文件中
with open("test.log", 'r') as obj1, open ("test2.log", 'w') as obj2: for line in obj1: obj2.write(line)
class file(object) def close(self): # real signature unknown; restored from __doc__ 關閉文件 """ close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for further I/O operations. close() may be called more than once without error. Some kinds of file objects (for example, opened by popen()) may return an exit status upon closing. """ def fileno(self): # real signature unknown; restored from __doc__ 文件描述符 """ fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read(). """ return 0 def flush(self): # real signature unknown; restored from __doc__ 刷新文件內部緩衝區 """ flush() -> None. Flush the internal I/O buffer. """ pass def isatty(self): # real signature unknown; restored from __doc__ 判斷文件是不是贊成tty設備 """ isatty() -> true or false. True if the file is connected to a tty device. """ return False def next(self): # real signature unknown; restored from __doc__ 獲取下一行數據,不存在,則報錯 """ x.next() -> the next value, or raise StopIteration """ pass def read(self, size=None): # real signature unknown; restored from __doc__ 讀取指定字節數據 """ read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. """ pass def readinto(self): # real signature unknown; restored from __doc__ 讀取到緩衝區,不要用,將被遺棄 """ readinto() -> Undocumented. Don't use this; it may go away. """ pass def readline(self, size=None): # real signature unknown; restored from __doc__ 僅讀取一行數據 """ readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. """ pass def readlines(self, size=None): # real signature unknown; restored from __doc__ 讀取全部數據,並根據換行保存值列表 """ readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned. """ return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__ 指定文件中指針位置 """ seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to (offset from start of file, offset should be >= 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable. """ pass def tell(self): # real signature unknown; restored from __doc__ 獲取當前指針位置 """ tell() -> current file position, an integer (may be a long integer). """ pass def truncate(self, size=None): # real signature unknown; restored from __doc__ 截斷數據,僅保留指定以前數據 """ truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell(). """ pass def write(self, p_str): # real signature unknown; restored from __doc__ 寫內容 """ write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written. """ pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__ 將一個字符串列表寫入文件 """ writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string. """ pass def xreadlines(self): # real signature unknown; restored from __doc__ 可用於逐行讀取文件,非所有 """ xreadlines() -> returns self. For backward compatibility. File objects now include the performance optimizations previously implemented in the xreadlines module. """ pass 2.x
class TextIOWrapper(_TextIOBase): """ Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be decoded or encoded with. It defaults to locale.getpreferredencoding(False). errors determines the strictness of encoding and decoding (see help(codecs.Codec) or the documentation for codecs.register) and defaults to "strict". newline controls how line endings are handled. It can be None, '', '\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. If line_buffering is True, a call to flush is implied when a call to write contains a newline character. """ def close(self, *args, **kwargs): # real signature unknown 關閉文件 pass def fileno(self, *args, **kwargs): # real signature unknown 文件描述符 pass def flush(self, *args, **kwargs): # real signature unknown 刷新文件內部緩衝區 pass def isatty(self, *args, **kwargs): # real signature unknown 判斷文件是不是贊成tty設備 pass def read(self, *args, **kwargs): # real signature unknown 讀取指定字節數據 pass def readable(self, *args, **kwargs): # real signature unknown 是否可讀 pass def readline(self, *args, **kwargs): # real signature unknown 僅讀取一行數據 pass def seek(self, *args, **kwargs): # real signature unknown 指定文件中指針位置 pass def seekable(self, *args, **kwargs): # real signature unknown 指針是否可操做 pass def tell(self, *args, **kwargs): # real signature unknown 獲取指針位置 pass def truncate(self, *args, **kwargs): # real signature unknown 截斷數據,僅保留指定以前數據 pass def writable(self, *args, **kwargs): # real signature unknown 是否可寫 pass def write(self, *args, **kwargs): # real signature unknown 寫內容 pass def __getstate__(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __next__(self, *args, **kwargs): # real signature unknown """ Implement next(self). """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 3.x
冒泡排序
#利用新變量互換值 a1 = 123 a2 = 456 temp = a1 a1 = a2 a2 = temp a1 = 456 a2 = 123
#實現列表元組互換 li = [11,33,22,44,55] temp = li[1] li[1] = li[2] li[2]=temp print(li) >>> [11,22,33,44,55]
#把列表裏面的全部值進行比較 li = [33,22,10,1] for i in range(len(li)-1): #循環列表次數 # i = 0 1 2 3 #current: li[0] 1 2 3 #next_value: li[1] 2 3 4 #列表li裏面沒有li[4],所以須要減小一次循環次數 current = li[i] next_value = li[i+1] print(i, current, next_value) >>> 0 33 2 #第一次循環 1 2 10 #第二次循環 2 10 1 #第三次循環
#循環一次列表,僅把一個最大的元素排在最右方
li = [33,2,10,1] for i in range(len(li)-1): #循環列表元素 if li[i] > li[i+1]: #元素互換的條件 temp = li[i] li[i] = li[i+1] li[i + 1] = temp print(li) >>> [2, 10, 1, 33]
li = [33,2,10,1] for i in range(len(li)-1): #元素內部從左往右循環比較三次,等於列表長度減1那麼屢次,如列表4個元素,兩兩比較,須要比較三次1-(33, 2), 2-(2,10), 3-(10, 1) if li[i] > li[i+1]: temp = li[i] li[i] = li[i+1] li[i + 1] = temp print(li) >>> [2,10,1,33]
li = [33,2,10,1] for j in range(1, len(li)): #因爲i循環每完成一次,下一次i循環排序的元素就減小一次, j的數值應爲1,2,3 到數列的長度爲止。 #j: 1 ,2 ,3, i循環中兩兩比較的次數 for i in range(len(li)-j): #元素內部循環比較完成一次,獲得最右邊的一個最大元素,下一次循環比較的元素就減小一個,j表明每次完成循環減小的排序的元素。 if li[i] > li[i+1]: temp = li[i] li[i] = li[i+1] li[i + 1] = temp print(li) >>> [1, 2, 10, 33]
遞歸
遞歸指的是這樣一個數列:一、一、二、三、五、八、1三、2一、……
遞歸知足2個條件:
1)有反覆執行的過程(調用自身)
2)有跳出反覆執行過程的條件(遞歸出口)
遞歸執行過程當中參數傳遞過程
def f1(): return "f1" #8. 執行f1(),返回"f1", f1返回給函數調用者f1()="f1"=>f2()=>f3()=>f4(),最後有ret接受返回值「f1」 def f2(): r = f1() #6. 執行f2(),獲得 r = f1() return r #7. r = f1(), 返回r,即返回執行f1() def f3(): r = f2() #4. 執行f3(),獲得 r = f2() return r #5. r = f2(), 返回r,即返回執行f2() def f4():
r = f3() #2.執行f4(),獲得 r = f3() return r #3.r = f3(), 返回r,即返回執行f3() ret = f4() # 1.解釋器讀取函數,把f1,f2,f3,f4的函數存入內存,執行函數f4(), ret接受f4返回值r
print(ret)
def f4(a1, a2): print(a1, a2) #a1 = 0, a2 = 1,a3 = 1 #a1 = 1, a2 = 1, a3 = 2 #a1 = 1, a2 = 2, a3 = 3 a3 = a1 + a2 # f4(a2, a3) #嵌套上面的參數循環執行函數 f4(0, 1) >>> 0 1 1 1 1 2 2 3 3 5 5 8 8 13 13 21 21 34 34 55 55 89 ...
練習:利用遞歸獲取斐波那契數列中的第 10 個數,並將該值返回給調用者。
def f5(depth, a1, a2): #depth數列的第n個數
if depth == 10: return a1 #數列第十個數的返回值,最終有啓始的函數'ret'接受 a3 = a1 + a2 r = f5(depth +1, a2, a3) return r ret = f5(1,0,1)#數值0爲第一個斐波那契的數值 print(ret) >>> 34
裝飾器
裝飾器用於裝飾某個函數或者方法或者類,在調用者調用方式不變的狀況下,能夠在函數執行前或執行後作其餘操做。
裝飾器本質,將 原函數 封裝到 新的函數裏面(),使執行新函數時,既能夠實現新函數的功能,有能夠執行就函數的功能。
def outer(func):#參數func = 以原來的f1函數做爲參數 def inner():#inner函數做爲新的f1函數執行 print("hello") r = func()#因爲outer(func)的參數爲f1,此處執行原來的f1函數 print("end") return r return inner #@outer inner = f1 @outer #f1 = outer(f1) 1.執行outer函數,而且將其下面的函數名f1當作參數,func = f1;
2.將outer的返回值inner從新賦值給f1,f1=(outer的返回值)=inner, 執行f1() = 執行inner() def f1(): print("F1")
return ooo def f2(): print("F2") def f3(): print("F3") """ . . . """ def f100(): print("F100")
f1() >>> hello F1 end
ooo
只要函數應用裝飾器,那麼函數就被從新定義爲:裝飾器的內層函數。
裝飾器裝飾含兩個參數的函數
def outer(func): def inner(a1, a2): print("123") ret = func(a1, a2) print("456") return ret return inner @outer #inner = index(a1, a2),index函數被裝飾到inner函數裏面, #執行index函數是須要兩個參數,所以裝飾器函數也須要兩個參數inner(a1,a2)。 #裝飾器內部執行func() = 執行index(),所以也須要在func函數中加入兩個參數。func(a1, a2) def index(a1, a2): print("執行函數") return a1 + a2 ret = index(1, 2) print(ret)
裝飾器裝飾含N個參數的函數
def f1(*args,**kwargs):#多參數函數 print(args) print(kwargs) f1(11, 22, 33, 44, 55, 66, 77, 88, k1=123, k2=321)
>>>
(11, 22, 33, 44, 55, 66, 77, 88)
{'k2': 321, 'k1': 123}
def outer(func): def inner(*args, **kwargs):# print(args) ret = func(*args, **kwargs)# print(kwargs) return ret return inner @outer def index(a1, a2, k1=123, k2=456): print("執行函數") return a1 + a2 ret = index(10, 20, k1=123, k2=456) print(ret) >>> (10, 20) 執行函數 {'k1': 123, 'k2': 456} 30
多個裝飾器裝飾同一個函數
def outer_0(func): def inner(*args, **kwargs): print("python 3.5") ret = func(*args, **kwargs) return ret return inner def outer(func): def inner(*args, **kwargs): print(args) ret = func(*args, **kwargs) print(kwargs) return ret return inner @outer_0 @outer def index(a1, a2, k1=123, k2=456): print("執行函數") return a1 + a2 >>> python 3.5 (10, 20) 執行函數 {'k1': 123, 'k2': 456} 30
多裝飾器嵌套原理
# @outer: inner = index, outer(func) = outer(index) # inner = 新的 index 函數 # index(*args, **kwargs): # print(args) # ret = index(*args, **kwargs) # print("執行函數") # return a1 + a2 # print(kwargs) # return ret #@outer0:inner = 新的 index 函數 + 新的 inner, outer0(func) = outer0(inner(index)) #inner =out0 + index(*args, **kwargs) 函數 + #index(*args, **kwargs): # print("python 3.5") # print(args) # print("執行函數") # return a1 + a2 # print(kwargs) # return ret
裝飾器總結 @
把index函數做爲outer的參數去執行outer函數
index的總體放入內存 當內層函數inner中對index進行調用它做爲一個新的函數
@outer
1. 執行outer函數,將index做爲參數傳遞
2. 將outer的返回值,從新賦值給index