打開文件的三種方式:
open(r'E:\學習日記\python\code\文件的簡單操作.py')
open('E:\\學習日記\\python\\code\\文件的簡單操作.py')
open('E:/學習日記/python/code/文件的簡單操作.py')
#字符串前面加一個r代表原生的raw
# rt,wt,at:r讀,w、a寫,t表示以文本打開
eg: >>> res = open(r'E:\test.txt','r',encoding='utf-8') >>> read = res.read() >>> print(read) >>> res.close() 123 小米 qwe asd
#文本形式讀取
with open(r'E:\test.txt','rt',encoding='utf-8') as f: #read(1)代表讀取一個字符,讀取光標往右的內容(默認光標在開頭) data1 = f.read(1) print(data1) data2 = f.read(1) print(data2) 1 2 #readline:按行讀取 data1 = f.readline() data2 = f.readline() print(data1) print(data2) 123 小米 #readlines:把內容以列表形式顯示 data = f.readlines() print(data) ['123\n', '小米\n', 'qwe\n', 'asd'] for a in data: print(a) 123 小米 qwe asd #readable:是否可讀(返回布爾類型) res = f.readable() print(res) True
文本形式寫
w:覆蓋寫
a:追加寫
with open(r'E:\test.txt','wt',encoding='utf-8') as res: #write:往文件里覆蓋寫入內容 res.write('謝謝你的愛1999') 謝謝你的愛1999(test.txt) #writelines:傳入可迭代對象變成字符串寫入文件 res.writelines(['qw','\n12','3er']) res.writelines({'name':'小米','age':23}) helloqw 123ernameage with open(r'E:\test.txt','at',encoding='utf-8') as res: #a模式write寫入為追加 res.write('\n456') helloqw 123ernameage 456 #writable:是否可寫 res.writable() True
rb,wb,ab
bytes類型讀
with open(r'E:\test.txt','rb') as res: a = res.read() print(a) b'hello\r\n\xe4\xbd\xa0\xe5\xa5\xbd' print(a.decode('utf-8')) hello 你好 # bytes類型寫: #1.字符串前面加b(不支持中文) # 2.encode with open(r'E:\test.txt', 'wb') as res: res.write(b'asd') asd res.write('你好'.encode('utf-8')) 你好
光標的移動
with open(r'E:\test.txt', 'wb') as res: #前面的數字代表移動的字符或字節,后面的數字代表模式(0:光標在開頭,1:代表相對位置,2:代表光標在末尾) res.seek(2,0) print(res.read()) e qwertyuiop res.seek(1,0) res.seek(2,1) print(res.read().decode('utf-8')) qwertyuiop res.seek(-3,2) print(res.read().decode('utf-8')) iop # tail -f /var/log/message | grep '404' #光標的移動用途之一
實例:
編寫一個用戶登錄程序
登錄成功顯示歡迎頁面
登錄失敗顯示密碼錯誤,並顯示錯誤幾次
登錄三次失敗后,退出程序
升級:
可以支持多個用戶登錄
用戶3次認證失敗后,退出程序,再次啟動程序嘗試登錄時,還是鎖定狀態
user = 'root' passwd = 'root' i = 0 print("請登錄:") while True: new_user = input("請輸入用戶:") new_passwd = input("請輸入密碼:") if new_user == user and new_passwd == passwd: print("歡迎光臨") break else: print("密碼輸入錯誤!") i +=1 if i == 3: print("三次輸入錯誤,退出程序") break