修改檔案內容

2021-09-02 09:45:15 字數 2497 閱讀 7505

import os

def fetch(data):

# print('使用者查詢資料: %s' % data)

backend_data = 'backend ' + data + '\n' # 讀取的文字有換行符,需要做下拼接

with open('haproxy.conf', 'r', encoding='utf-8') as read_file: # 使用with開啟檔案不用手動關閉

tag = false # 是否匹配到使用者查詢內容,作為開始儲存和結束標誌

ret = # 用於儲存查詢成功讀取的內容

for v in read_file: # 一行一行遍歷檔案內容

if v == backend_data: # 匹配到使用者查詢內容行

tag = true # 設定開始儲存標誌true

continue # 不列印,本次迴圈結束,繼續執行下次迴圈

if tag and v.startswith('backend'): # 是否讀取結束

break # 迴圈結束

if tag:

print(v, end='')

return ret

def add():

pass

def change(data):

# print('這是修改功能:')

# print('使用者輸入的資料是 %s' % data)

backend = data[0]['backend']

record = data[0]['record']

print(record)

old_server_record = '%sserver %s weight %s maxconn %s\n' % (' '*8, record['server'], record['weight'], record['maxconn'])

res = fetch(backend)

if not res or old_server_record not in res:

return '修改的記錄不存在!'

else:

index = res.index(old_server_record)

record_1 = data[1]['record']

res[index] = '%sserver %s weight %s maxconn %s\n' % (' ' * 8, record_1['server'], record_1['weight'], record_1['maxconn'])

with open('haproxy.conf', 'r', encoding='utf-8') as read_f, open('haproxy_new.conf', 'w', encoding='utf-8') as write_f:

tag = false

for line in read_f:

if tag and line.startswith('backend'):

tag = false # 如果是改寫內容,並且到了改寫內容結束位置

if tag:

continue # 如果是改寫內容,跳過不執行,繼續下一次迴圈

if line == 'backend %s\n' % backend:

tag = true

write_f.write(line)

if tag:

write_f.writelines(res)

# os.rename('haproxy.conf', 'haproxy.conf.bak')

os.remove('haproxy.conf')

os.rename('haproxy_new.conf', 'haproxy.conf')

# os.remove('haproxy.conf.bak')

def delete():

pass

if __name__ == '__main__': # 只有在乙個檔案單獨執行時會執行,防止引用時執行

msg='''

1:查詢

2:新增

3:修改

4:刪除

5:退出

'''msg_dic =

while 1:

print(msg)

choice = input('請輸入你的選項').strip() # 去除兩邊空格和換行符

if not choice:

continue

if choice == '5': # 使用者選擇退出,執行推出操作

exit()

data = input('請輸入查詢內容').strip()

if data != '1':

data = eval(data) # 除了查詢之外的操作,都對輸入的字串進行轉換提取資料結構

res = msg_dic[choice](data) # 執行msg_dic對應的函式

print(res) # 列印執行函式的返回值

# [}, }]

用python修改檔案內容修改txt內容的3種方法

用python修改檔案內容修改txt內容的3種方法 方法一 修改原檔案方式 def updatefile file old str,new str 替換檔案中的字串 param file 檔名 param old str 就字串 param new str 新字串 return file data ...

用python修改檔案內容修改txt內容的3種方法

用python修改檔案內容修改txt內容的3種方法 方法一 修改原檔案方式 def updatefile file,old str,new str 替換檔案中的字串 param file 檔名 param old str 就字串 param new str 新字串 return file data ...

txt檔案內容修改

1 新建乙個檔案,然後寫入內容,再關閉 2 開啟之前新建的檔案,再新建乙個檔案。讀一行,如果不用修改則直接向新檔案寫這一行的內容,否則寫修改之後的內容 注意line.replace 一定要寫成line line.replace 否則不會更換。程式執行的結果 coding utf 8 功能 1 新建乙...