python增删改查csv文件_【练习】Python第四次:实现对文件的增删改查
import os #os包含改名和刪除文件函數(shù)
def file_handler(backend_data,res = None,type='fetch'):if type == 'fetch':
with open('haproxy.conf', 'r') as read_f:
tag= False #找到標志
ret =[]for read_line inread_f:if read_line.strip() == backend_data: #匹配到數(shù)據(jù)
tag =Truecontinue
if tag and read_line.startswith('backend'): #到下一個backend停止
break
if tag: #找到后讀出后面的數(shù)據(jù)
print('%s' % read_line, end='')
ret.append(read_line)returnretelif type == 'change':
with open('haproxy.conf', 'r') as read_f, \
open('haproxy.conf_new', 'w') as write_f:
tag=False
has_write=Falsefor read_line inread_f:if read_line.strip() ==backend_data:
tag=Truecontinue
if tag and read_line.startswith('backend'):
tag=Falseif nottag:
write_f.write(read_line)else:if nothas_write:for record inres:
write_f.write(record)
has_write=True
os.rename('haproxy.conf', 'haproxy.conf.bak')
os.rename('haproxy.conf_new', 'haproxy.conf')
os.remove('haproxy.conf.bak')deffetch(data):#print('這是查詢功能')
#print('用戶數(shù)據(jù)是',data)
backend_data ='backend %s' %datareturnfile_handler(backend_data)defadd():pass
#[{'backend':'www.oldboy1.org','record':{'server':'2.2.2.4','weight':20,'maxconn':3000}},{'backend':'www.oldboy1.org','record':{'server':'2.2.2.5','weight':30,'maxconn':4000}}]
defchange(data):#print('這是修改功能')
#print('用戶輸入數(shù)據(jù)是:',data)
backend = data[0]['backend'] #從用戶傳參提取www.oldboy1.org
backend_line = 'backend %s' %data[0]['backend']#內(nèi)容:backend www.oldboy1.org
#拼接字符串old_server_record,把用戶傳參的源server信息整理出來
old_server_record = '%sserver %s %s weight %s maxconn %s\n' %(' '*8,data[0]['record']['server'],
data[0]['record']['server'],
data[0]['record']['weight'],
data[0]['record']['maxconn'])#用戶傳參的目標server信息
new_server_record = '%sserver %s %s weight %s maxconn %s\n' %(' '*8,data[1]['record']['server'],
data[1]['record']['server'],
data[1]['record']['weight'],
data[1]['record']['maxconn'])print('用戶想要修改的記錄是:',old_server_record)
res=fetch(backend)print('來自change函數(shù)結(jié)果--》',res)if not res or old_server_record not inres:return '你要修改的記錄不存在'
else:
index=res.index(old_server_record)
res[index]=new_server_record
res.insert(0,'%s\n' %backend_line)
file_handler(backend_line,res=res,type='change')defdelete():pass
#Python文件里面只寫不會運行的功能,測試代碼在下面寫
if __name__ == '__main__':
msg='''1:查詢
2:添加
3:修改
4:刪除
5:退出'''msg_dic={'1':fetch,'2':add,'3':change,'4':delete,
}whileTrue:print(msg)
choice= input('請輸入你的選項:').strip()if not choice:continue
if choice == '5':breakdata= input('請輸入你的數(shù)據(jù):').strip()if choice != '1': #查詢輸入的是字符串,其他需要處理格式化數(shù)據(jù)
data =eval(data)
res=msg_dic[choice](data)print('最終結(jié)果是————》',res)
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的python增删改查csv文件_【练习】Python第四次:实现对文件的增删改查的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA输出菱形并使用绝对值,案例用绝对
- 下一篇: python给js变量赋值_python