知識點一、文件讀寫內容
-
1、當文件當前沒有寫文件模式,默認為r,當文件以r的形式打開不存在的文件會報錯
1 f = open('a.txt') 2 f = open('a.txt','r',encoding = 'utf-8')
文件內容:
yangmingyue
xiaohong
xiaomgg 23434
dakggak
-
(1)read
1 f = open('a.txt','r',encoding = 'utf-8')#當前沒有寫文件模式,默認為r 2 print('read',f.read())#讀出文件所有內容,文件內容為字符串
-
(2)readlines
1 f = open('a.txt','r',encoding = 'utf-8')#當前沒有寫文件模式,默認為r 2 print('readlines',f.readlines())#讀出文件所有內容,把文件每一行內容放在list中
-
(3)readline
1 f = open('a.txt','r',encoding = 'utf-8')#當前沒有寫文件模式,默認為r 2 print('readline',f.readline())#一次只讀一行
-
(4)文件指針:控制文件讀到的位置
1 f = open('a.txt','r',encoding = 'utf-8')#當前沒有寫文件模式,默認為r 2 print('readlines',f.readlines())#讀出文件所有內容,把文件每一行內容放在list中 3 print('readline',f.readline())#一次只讀一行
1 f = open('a.txt','r',encoding = 'utf-8') 2 print('readlines',f.readlines()) 3 print('read',f.read())
1 f = open('a.txt','r',encoding = 'utf-8')#當前沒有寫文件模式,默認為r 2 print('readline',f.readline())#一次只讀一行 3 print('readlines',f.readlines())#讀出文件所有內容,把文件每一行內容放在list中
-
2、當文件以w的模式寫入文件,能寫不能讀,寫之前會清空文件(1)write 寫入內容是字符串,就用write,
1 f = open('a.txt','w') 2 f.write('asdeeff\n')#只能寫字符串 3 f.close()

-
(2)writelines 寫入list時用
1 f = open('a.txt','w') 2 f.writelines('6747888')#可以寫list,自動循環list每個元素,將元素都寫入文件,也可以寫入集合,只能能循環的數據類型都可以寫 3 f.close()

1 stus = ['xiaohong','xiaobei','xiaolan'] 2 f = open('a.txt','w') 3 f.writelines(stus)#可以寫list,自動循環list每個元素,將元素都寫入文件 4 f.close()
1 set = {'xiaohong','xiaohei','xuangg'} 2 f = open('a.txt','w') 3 f.writelines(set)#可以寫list,自動循環list每個元素,將元素都寫入文件 4 f.close()
-
3、當文件以a 的模式打開不存在的文件,會追加生成新的文件,不會報錯
1 f = open('a.txt','a',encodinga = 'utf-8')
-
4、r+ 能讀能寫,打開不存在文件報錯
1 f = open('a.txt','r+',encoding = 'utf-8') 2 print(f.read()) 3 f.write('r+模式222333') 4 f.close()
1 f = open('a.txt','r+',encoding = 'utf-8') 2 #print(f.read()) 3 f.write('r+模式4444') 4 f.close()
注意:
讀與不讀會影響寫的位置,因為文件指針導致的
-
5、w+ 能讀能寫,但是會清空之前的文件,
1 f = open('a.txt','w+',encoding = 'utf-8') 2 print(f.read()) 3 f.write('r+模式4444') 4 f.close()
1 f = open('a.txt','w+',encoding = 'utf-8') 2 f.write('r+模式4444') 3 print(f.read()) 4 f.close()
注意:寫完之后讀不到東西,想要想要讀到內容,移動文件指針,f.seek(0)
-
6、a+ 能讀能寫不會清空之前的文件
1 f = open('a.txt','a+',encoding = 'utf-8') 2 print(f.read()) 3 f.write('r+模式4444') 4 f.close()d
注意:讀不到東西,文件指針導致,想要讀到內容,移動文件指針,f.seek(0)
1 f = open('a.txt','a+',encoding = 'utf-8') 2 f.seek(0) 3 print(f.read()) 4 f.write('r+模式4444') 5 f.close()
總結:
-
高效讀文件:打開文件,直接循環文件對象
1 f = open('a.txt',encoding='utf-8') 2 3 for line in f: 4 print('每一行的內容:',line)

-
列子:
1 #1、監控服務器日志,找出每分鍾訪問超過100次的ip地址 2 #分析: 3 #1、當前時間去讀上一分鍾的數據,死循環 while True 實現,讀取文件,獲取到文件里面的所有ip地址 4 #2、把ip地址存起來,用字典存,key是ip地址,value是次數 5 #3、循環字典,判斷value大於100的 6 7 import time 8 point = 0 9 while True: 10 ips = {} # 存放所有的ip地址以及它出現的次數 11 f = open('access.log')#默認r 的模式,讀出所有的文件內容 12 f.seek(point)#文件指針到文件頭 13 for line in f: 14 if line.strip():#判斷不為空行的時候 15 ip = line.split()[0] 16 if ip not in ips: 17 ips[ip] = 1 18 else: 19 ips[ip] = ips[ip]+1 20 point = f.tell() #當前文件指針的位置 21 for ip in ips: 22 if ips.get(ip) >= 100: 23 print('超過100次的ip是:%s'%ip) 24 time.sleep(60)
知識點二、文件修改
-
#方式一:先讀文件,替換,將替換的文件寫入文件
1 f = open('a.txt','a+',encoding='utf=8') 2 result = f.read() 3 new_result = result.replace('abc','ABC') 4 f.seek(0) 5 f.truncate()#清空文件內容 6 f.write(new_result) 7 f.close()
-
#方式二:一次讀一行,一行一行修改
1 #import os 2 # f1 = open('test.txt',encoding="utf-8") 3 # f2 = open('a2.txt','w',encoding='utf-8') 4 # for line in f1: 5 # new_line = line.replace('-','1') 6 # f2.write(new_line) 7 # f1.close() 8 # f2.close() 9 # os.remove('test.txt') 10 # os.rename('a2.txt','test.txt')
-
#方法三:使用with 不用自己關閉文件
1 import os 2 with open('a1.txt',encoding='utf-8') as f1,open('a2.txt','w',encoding='utf-8') as f2: 3 for line in f1: 4 new_line = line.replace('-', '1') 5 f2.write(new_line) 6 7 os.remove('a1.txt') 8 os.rename('a2.txt', 'a1.txt')
程序明明運行完,文件中沒有內容,原因是不同的區域運行速度不一致,處理方式:
1 with open ('a.txt','w')as fw: 2 fw.write('123') 3 fw.flush()#處理文件運行后沒有內容
知識點三、非空即真,非0即真,判斷的時候使用給,簡化代碼
1 s = ''#字符串 2 l = []#數組 3 d = {}#字典 4 s1 = set()#集合 5 6 username = input('user').strip() 7 if username:#表示內容不為空 8 print('歡迎登錄') 9 else: 10 print('輸入內容不能為空') 11 12 if not username:#表示沒有內容,內容為空
知識點四、json 文件
json串就是字符串
1 d = {"name":"abc"} 2 import json 3 import pprint 4 json_str = json.dumps(d) #就是把字典/list轉成字符串(json) 5 pprint.pprint(json_str)
效果:把字典轉成字符串,用pprint,效果更明顯
1 json_str2 = ' {"xiaohei":"123456","age":18} ' 2 dic = json.loads(json_str2) #把字符串(json)轉成 字典 3 pprint.pprint(dic)

1 d = {"xiaohong":"123456","age":18} 2 with open('users.json','w',encoding='utf-8') as f: 3 json_d = json.dumps(d)#把字典轉成字符串 4 f.write(json_d)

1 with open('users','r',encoding='utf-8') as f: 2 result = f.read() 3 a = json.loads(result)#把字符串轉成字典 4 pprint.pprint(a)

1 d = { 2 "id": 314, 3 "name": "礦泉水", 4 "sex": "男", 5 "age": 18, 6 "addr": "北京市昌平區", 7 "grade": "摩羯座", 8 "phone": "18317155663", 9 "gold": 40 10 } 11 with open('user','w',encoding = 'utf-8') as f: 12 json_b = json.dumps(d,ensure_ascii=False,indent=4)#ensure_ascii=False讀出中文,indent=4縮進格式化 13 f.write(json_b)

1 d = { 2 "id": 314, 3 "name": "礦泉水", 4 "sex": "男", 5 "age": 18, 6 "addr": "北京市昌平區", 7 "grade": "摩羯座", 8 "phone": "18317155663", 9 "gold": 40 10 } 11 with open('user.json','w',encoding = 'utf-8') as f:#打開json 文件后,寫入格式有顏色區分 12 json_b = json.dumps(d,ensure_ascii=False,indent=4)#ensure_ascii=False讀出中文,indent=4縮進格式化,4表示4個縮進 13 f.write(json_b)

1 import json 2 import pprint 3 d = { 4 "id": 314, 5 "name": "礦泉水", 6 "sex": "男", 7 "age": 18, 8 "addr": "北京市昌平區", 9 "grade": "摩羯座", 10 "phone": "18317155663", 11 "gold": 40 12 } 13 f = open('users','w',encoding= 'utf-8') 14 json.dump(d,f,ensure_ascii=False,indent = 4)
1 f = open('users','r',encoding= 'utf-8') 2 dic = json.load(f) 3 print(dic)
知識點五、函數
-
#函數就是把一段代碼封裝起來,函數的作用就是簡化代碼
-
#告訴文件名和內容
1 def write_file(file_name,content): 2 f = open(file_name,'w') 3 f.write(content) 4 f.close()
-
#函數里面定義的變量都是局部變量,只在函數里面可以用,出了函數就不能用了
1 def read_file(file_name): 2 with open(file_name,encoding='utf-8') as fr: 3 result = fr.read() 4 return result #函數返回值 5 6 content = read_file('users')#函數調用 7 # print(content)
#1、函數不寫返回值的情況下返回的是空
#2、返回多個值的時候,返回的是什么
#函數里面遇到return函數立即結束運行
函數例子:
1 #判斷是否是浮點數的函數方法 1.33,-4.5 正數負數都是浮點數 2 #1、必須只有一個小數點 3 #2、小數點的左邊必須是整數,小數點的右邊必須是正整數 4 def is_float1(s): 5 s = str(s) #.1 6 if s.count('.')==1:#小數點數量為1 7 left,right = s.split('.') #['-','1']左側和右側用小數點分割 8 if left.isdigit() and right.isdigit():#左右都是正整數 9 return True#表示正浮點數 10 elif left[0] == '-' and left[1:].isdigit() and right.isdigit():#左邊的第一個元素是-,左邊的第一個元素后和右邊的元素都是正整數 11 return True#表示是負的浮點數 12 else: 13 return False#不是浮點數 14 else: 15 return False#不是浮點數 16 print(is_float1('-.1')) # 函數調用 17 print(is_float1('-1.1')) # 函數調用 18 print(is_float1('1.1')) # 函數調用 19 print(is_float1('s.1')) # 函數調用 20 print(is_float1('-s.1')) # 函數調用

簡化后的代碼
1 def is_float1(s): 2 s = str(s) #.1 3 if s.count('.')==1:#小數點數量為1 4 left,right = s.split('.') #['-','1']左側和右側用小數點分割 5 if left.isdigit() and right.isdigit():#左右都是正整數 6 return True#表示正浮點數 7 elif left[0] == '-' and left[1:].isdigit() and right.isdigit():#左邊的第一個元素是-,左邊的第一個元素后和右邊的元素都是正整數 8 return True#表示是負的浮點數 9 10 return False#不是浮點數
簡化的原因是只有不符合浮點數規則,都是返回False
print(is_float1(.1))會報錯
1 def is_float1(s): 2 s = str(s) #.1 3 if s.count('.')==1: 4 left,right = s.split('.') #['-','1'] 5 if left.isdigit() and right.isdigit():#正小數 6 return True 7 elif left.startswith('-') and left.count('-')==1 and right.isdigit(): 8 #先判斷負號開頭,只有一個負號,小數點右邊是整數 9 lleft = left.split('-')[1] #如果有負號的話,按照負號分隔,取負號后面的數字 10 if lleft.isdigit():# 11 return True 12 return False 13 print(is_float1(.1))

1 s='1.1' 2 def is_float(s): 3 s = str(s) 4 if s.count('.') == 1: # 判斷小數點個數 5 left,right = s.split('.') # 按照小數點進行分割 6 if left.startswith('-') and left.count('-') == 1 and right.isdigit(): 7 lleft = left.split('-')[1] # 按照-分割,然后取負號后面的數字 8 if lleft.isdigit(): 9 return True 10 elif left.isdigit() and right.isdigit():# 判斷是否為正小數 11 return True 12 return False 13 print(is_float(s))

1 def hhh(name): #默認值參數 2 print(name) 3 #默認值函數的參數不是必傳的, 4 def op_file(file_name,content=None):#(必填參數,默認值參數) 5 if content: 6 f = open(file_name,'w',encoding='utf-8') 7 f.write(content) 8 else: 9 f = open(file_name,encoding='utf-8') 10 return f.read() 11 def abc(name,age,phone,addr,money):# 12 print(name) 13 print(age) 14 print(phone) 15 print(addr) 16 print(money) 17 abc('xiaohei',18,110,'beijing',9000)#按照位置順序傳 18 abc(age=18,addr='beijing',money=500,phone=111,name='111')#指定參數 19 abc('xiaobai',addr='123',phone=1111,money=11111,age=13)#順序,指定參數 20 abc(age=13,'xiaohei')#指定參數,按照位置這種傳參方式是不對滴
-
全局變量:公共的變量
1 file_name = 'users.json' #全局變量 2 def func(): 3 file_name = 'abc.json' 4 print(file_name) 5 func() 6 7 print(file_name)

修改全局變量的方法
1 file_name = 'users.json' #全局變量 2 def func(): 3 global file_name#聲明修改的全局變量 4 file_name = 'abc.json' 5 print(file_name) 6 func() 7 print(file_name)

例子:
1 money = 500 2 def test(consume): 3 return money - consume 4 5 def test1(money): 6 return test(money) + money
-
#常量:不會變的變量,常用大寫字母定義
1 PI = 3.14