username,12345678 username2,abc12345
用戶註冊json
#1.註冊: #用戶和密碼存在文件裏面 #username,123456 #username2,abc123 #讀寫文件 #1.要從文件裏面取出來全部的用戶名 #2.若是不存在就寫入,存在就報用戶名已註冊 f = open("users.txt",'a+') #f.seek(0) res = f.read() all_user_name = [] #存放全部的用戶名 for r in res.split('\n'): #['username,123456','username2,abc123'] #'username,123456' username = r.split(',')[0] all_user_name.append(username) for i in range(3): username = input('username:').strip() pwd = input('pwd:').strip() cpwd = input('cpwd:').strip() if not(len(username) > 6 and len(username) < 20): print("用戶名長度不合法") elif not (len(pwd) >=8 and len(pwd) <= 20): print("密碼長度不合法") elif pwd != cpwd: print("兩次輸入的密碼不一致") elif username in all_user_name: print("用戶名已經註冊") else: user_info = '%s,%s\n'%(username,pwd) f.write(user_info) print("註冊成功") break f.close()
用戶登錄app
# 用戶從user.txt 中讀取賬戶和密碼進行登錄 # res = open('users.txt').read() # username = input('username:') # pwd = input("pwd:") # user_info = username+','+pwd # if user_info in res: # print("登錄成功") # else: # print("登錄失敗,賬號或密碼錯誤") # all_user = {} res = open('users.txt').read() for r in res.split('\n'): #['username,12345678','username2,abc12345'] #'username,12345678' ['username,12345678'] if r.strip() != '': username = r.split(',')[0] pwd = r.split(',')[1] all_user[username] = pwd for i in range(3): username = input("username:") pwd = input('pwd:') if username in all_user: #if pwd == all_user.get(username): if pwd == all_user[username]: print("歡迎登陸!") else: print("賬號/密碼錯誤!") else: print("該用戶未註冊")
r:只讀,文件不存在,會報錯
w: 只寫,會清空原有內容,文件不存在會新建
a: 追加寫,不會清空,文件不存在會新建
r+: 讀寫模式,文件不存在會報錯
w+: 寫讀模式,文件不存在會建立,文件會被刪除後重寫
a+: 追加讀模式,文件不存在會建立,文件只會被追加
rb、wb、ab: 以二進制方式,多用於圖像,多媒體數據等
文件讀編碼
f = open('users.txt') print(f.read()) #獲取到文件裏面全部的內容 print(f.read()) #再次讀時會讀不到內容 print(f.readlines()) #文件中全部內容,返回爲list,文件中每行分別爲一個元素 print(f.readline()) #一次讀取一行內容
文件寫指針
f1 = open('users.txt','a') a=['username1,123456\n','usrname2,123456\n'] for i in a: f1.write(i) #每次寫入一行 f1.writelines(a) #writelines()方法用於將list寫入文件
文件訪問次數記錄練習日誌
# 1.要從日誌中訪問超過200次的 # 2.每分鐘都運行一次 #思路: # 1.讀取文件內容,獲取IP地址 # 2.把每一個IP地址存起來 #['192.168.1.1','192.168.1.2','192.168.1.3'] # 3.以字典方式存{'192.168.1.1':2,'192.168.1.3':5} #判斷ip訪問次數超過200次,若是字典的value超過200,加入黑名單 import time point = 0 #初始的位置 while True: ips = {} f = open('access.log',encoding='utf-8') f.seek(point) for line in f: #循環讀取文件裏面每行數據 ip = line.split(' ')[0] #按照空格分隔,取第一個元素ip if ip in ips: #判斷這個IP是否存在 ips[ip] += 1 #如存在,次數+1 else: ips[ip] = 1 #不存在,IP次數爲1 point = f.tell() #記錄文件指針位置 f.close() for ip,count in ips.items(): #循環這個字典,判斷次數大於200的 if count >= 200: print("%s 加入黑名單"%(ip)) time.sleep(60)
高效處理文件code
f = open('access.log',encoding='utf-8') #f叫文件對象或文件句柄 #第一種用while循環 while True: line = f.readline() #一次只取一行 if line != '': print(line) else: print("文件內容讀完,結束") break #第二種直接遍歷文件 for line in f: print(line)
修改文件內容對象
#簡單直接的方式 f = open(r'D:\file.txt',encoding='utf-8') res = f.read().replace('一點','二點') f.close() f = open(r'D:\file.txt','w',encoding='utf-8') f.write(res) f.close()
#方式二 f1 = open('file.txt','w+',encoding='utf-8') f1.seek(0) res = f1.read().replace('一點','hello') f1.seek(0) f1.truncate() #清空文件裏的內容 f1.write(res) f1.close()
import os f2 = open('file.txt',encoding='utf-8') f3 = open('file.txt.bak','w',encoding='utf-8') for line in f2: new_line = line.replace('NI','NIIIIIIII') f3.write(new_line) f2.close() f3.close() os.remove('file.txt') os.rename('file.txt.bak','file.txt')
import os with open('file.txt',encoding='utf-8') as f1, open('file.txt.bak','w',encoding='utf-8') as f2: #使用with時,文件不用就會被自動關閉,可同時打開多個文件 for line in f1: new_line = line.replace("二點",'一點') f2.write(new_line) os.remove('file.txt') os.replace('file.txt.bak','file.txt')
JSON是一種通用的數據類型,全部的語言都認識
JSON是字符串
方法以下:ip
若是涉及到文件,使用load()和dump()更方便utf-8
字符串轉成字典 s = ''' { "error_code": 0, "stu_info": [ { "id": 8410, "name": "小黑1", "sex": "男", "age": 28, "addr": "河南省濟源市北海大道32號", "grade": "天蠍座", "phone": "13488709889", "gold": 10401 }, { "id": 11089, "name": "小黑1", "sex": "男", "age": 28, "addr": "河南省濟源市北海大道32號", "grade": "天蠍座", "phone": "18612511124", "gold": 100 } ] } ''' import json res = json.loads(s) #json串(字符串),轉成字典 print(res) print(res.keys) print(type(res))
字典轉爲字符串 stus = {'xiaojun':'123456','xiaohei':'7891','xiaoliu':'111111','海龍':'111'} res2 = json.dumps(stus, indent=4,ensure_ascii=False) #indent爲縮進,中文默認使用的ascii編碼,中文須要ensure_ascii=False print(res2) print(type(res2)) with open('stus.json','w',encoding='utf-8') as f: f.write(res2)
能夠經過讀取文件中內容,將字符串轉爲字典 f = open('stus.json',encoding='utf-8') content = f.read() user_dict = json.loads(content) print(user_dict)
可能直接通用load(),傳入文件對象將字符串轉爲字典 f = open('stus.json', encoding='utf-8') user_dict = json.load(f) #load()能夠直接傳入一個文件對象 print(user_dict)
使用dump()傳入字典和文件對象將字典轉爲字符串 stus = {'xiaojun':'123456','xiaohei':'7891','xiaoliu':'111111','海龍':'111'} f = open('stus2.json','w',encoding='utf-8') json.dump(stus, f, indent=4, ensure_ascii=False)