標籤:一個 括弧 原來 程式 5.4 als access 引號 基礎
1 檔案讀寫補充
檔案修改
方法1:簡單粗暴直接:
1、 先擷取到檔案裡面的所有內容
2、 然後修改檔案裡面的內容
3、 清空原來檔案裡面的內容
4、 重新寫入
f = open(‘test1.txt‘,‘r+‘)
f.seek(0)
all_data = f.read()
new_data = all_data.replace(‘123‘,‘python‘)
f.seek(0) #將指標移到最前面
f.truncate() #清空原來檔案內容
f.write(new_data) #重新寫入檔案內容
f.flush()
f.close()
方法2:高效的處理方式
1、 先開啟原來的檔案,再開啟一個空檔案
2、 迴圈處理原來檔案裡每一行資料,處理完之後寫到新檔案裡
3、 將原來的檔案刪除,將新檔案名稱字修改成原來檔案的名字
import os
with open(‘words.txt‘) as fr,open(‘words1‘,‘w‘) as fw:
for line in fr:
line = line.lstrip() #去掉左邊的空格
if line: #判斷這一行是否有資料
line = line.replace(‘你‘,‘you‘) #替換資料
fw.write(line) #寫到新檔案裡面
os.remove(‘words.txt‘) #刪除原來的檔案
os.rename(‘words1‘,‘words.txt‘) #將新檔案重新命名為原來檔案名稱
使用with open方法開啟檔案會自動關閉,不需要在手動去關閉這個檔案;
f = open(‘筆記.txt‘) #開啟的檔案稱為檔案控制代碼或檔案對象
for line in f: #直接迴圈檔案對象,每次迴圈的時候就是去的每一行資料
print(‘line‘,line)
2 集合、json模組
集合作用:
1、 天生去重
2、 關係測試-交集,差集,並集,反向差集,對稱差集
nums = [1,2,3,2,3,4,1,5,6]
print(set(nums))
list = [1,2,3,4,5,3,6] #列表
list_dict = {2,3,4,3}
list_2 = [2,3,5,7,8]
list = set(list) #將列錶轉換為集合
list_2 = set(list_2)
print(‘交集:‘,list.intersection(list_2)) #交集,取出重複資料
print(list & list_2) #這個也叫交集
print(‘並集:‘,list.union(list_2)) #並集,去重統一展示
print(list | list_2) #這個也叫並集
print(‘差集:‘,list.difference(list_2)) #差集,取出list中有的,list_2中沒有的
print(list - list_2) #這個也叫差集
list_3 = set([1,3,6])
print(‘子集:‘,list_3.issubset(list)) #子集,list_3的值在list中全有,返回的是一個布爾類型的結果
print(‘父集:‘,list.issuperset(list_3)) #父集
print(‘對稱差集:‘,list.symmetric_difference(list_2)) #對稱差集,將list和list_2中互相沒有的值都取出來,把兩集合裡都有的去掉
print(list ^ list_2) #這個也叫對稱差集
#集合操作
list.add(123) #每次只能添加一個
print(list)
list.update([888,999]) #可以同時添加多個
print(list)
list.remove(999) #刪除指定元素
print(list)
list.pop() #隨機刪除
print(list)
list.discard() #刪除一個不存在的元素不會報錯
print(list)
執行個體:
#監控日誌
#1、如果一分鐘之內某個ip訪問超過100次
#2、就把他的ip找出來,split,取第一個元素
#3、找出所有的ip,統計次數
#4、判斷每個ip次數大於100,就發郵件
#5、記錄檔案指標,給下一次讀的時候用
#6、等待60s,重新讀取檔案
import time
point = 0 #存放的是檔案初始的位置
while True:
with open(‘access.log‘) as f:
f.seek(point)
ip_info = {} #存放ip和它出現的次數
for line in f:
ip = line.split()[0]
if ip in ip_info:
#ip_info[ip] = ip_info[ip] + 1
ip_info[ip] += 1
else:
ip_info[ip] = 1
point =f.tell() #擷取當前檔案指標的位置
for k in ip_info:
if ip_info.get(k)>= 100:
print(‘該ip在攻擊你%s‘%k)
time.sleep(60) #等待60s
json是一個字串,只不過長的像字典;
在json裡只有雙引號,沒有單引號;
import json
user_info = ‘‘‘
{"test1":"123456","test2":"123456"}
‘‘‘
user_dic =json.loads(user_info) #把json串(字串)轉換成字典
print(user_dic)
print(‘user_info‘,type(user_info))
print(‘user_dic‘,type(user_dic))
stu_info = {‘zhangsan‘:{‘cars‘:[‘BMW‘,‘Ben-z‘]}}
stu_str = json.dumps(stu_info) #把字典轉換成json串
print(‘stu_str‘,type(stu_str))
print(stu_str)
f = open(‘stu.txt‘,‘w‘)
f.write(stu_str)
f.close()
f = open(‘stu.json‘, ‘w‘)
json.dump(stu_info,f,indent=4) #不需要自己在write,人家會幫你寫入檔案,後面加入indent=4幫你自動進行縮排,4表示縮排4個字元
3 函數
1、函數就是一個功能,一個方法,簡化代碼
2、函數必須得調用才會執行
3、一個函數只做一件事
4、重複的代碼是低級的
5、實現同樣的功能,代碼越少越好
def say(name): #函數名,括弧裡寫參數就是形參(形式參數即變數)
print(‘%s hahaha‘%name) #函數體
say(‘zhangshan‘) #函數名裡面加括弧就是調用上面的函數,括弧裡面的參數是實參(實際參數)
def say1(name,sex=‘男‘): #函數名,括弧裡寫參數就是形參(形式參數即變數)
#必填參數,如name
#預設值參數,非必填,如sex=‘男‘
print(‘%s hahaha 性別%s‘%(name,sex)) #函數體
say1(‘zhangshan‘) #函數名裡面加括弧就是調用上面的函數,括弧裡面的參數是實參(實際參數)
在函數裡面的變數都是局部變數,它只能在函數裡面使用,函數執行結束就沒有這個變數了;
傳回值,如果需要用到函數的處理結果的話,就寫return,不需要的話,那就不用寫;函數裡面如果碰到return,函數立即結束;
# 函數立即結束def calc(a,b):
res = a * b
print(res)
return res #沒有return返回時,函數返回的資料類型就是NoneType,有return的類型就是函數的結果類型
cur_money = 8000
nx =calc(1000,13)
print(nx+cur_money)
defmy():
for i in range(100)
if i == 2:
return
print(my())
#寫一個校正輸入的字串是否為小數的程式
#思路:
# 1、0.12 1.23 -12.3只有一個小數點,判斷小數點個數;
# 2、正小數的情況下,小數點左邊和右邊都是整數的話,才合法,通過分割符去判斷
#3、負小數的情況下,小數點右邊整數,左邊必須是“-”開頭,且只有一個負號;
#-5.4
#[‘-5‘,‘4‘]
#[1:]
def check_float(s):
s = str(s)
if s.count(‘.‘) == 1:
s_list = s.split(‘.‘)
#5.3 分割之後就是[5,3]
left = s_list[0] #小數點左邊
rigth = s_list[1] #小數點右邊
if left.isdigit()and rigth.isdigit():
return True
elif left.startswith(‘-‘) and left.count(‘-‘) ==1and left[1:].isdigit() and rigth.isdigit():#left.count(‘-‘) ==1這個判斷可以不用寫
return True
return False
print(check_float(1.8))
print(check_float(-2.4))
print(check_float(‘-s.5‘))
print(check_float(‘50.232ss‘))
print(check_float(-3-4.4-9))
def my_file(name,content=None):
with open(name,‘a+‘) as f:
f.seek(0)
if content:
f.write(content)
else:
return f.read()
python基礎學習3-檔案讀寫、集合、json、函數