簡體   English   中英

python 替換文本文件中的多個字符串

[英]python replace multiple string in a text file

我有一個包含以下信息的文本文件:

 network={
      ssid="WIFI_SSID"
      scan_ssid=1
      psk="WIFI_PASSWORD"
      key_mgmt=WPA-PSK
}

我想修改這個文本文件並更改 ssid 和 psk 值。 所以我想要這樣的東西:

network={
      ssid="KB150"
      scan_ssid=1
      psk="testpass"
      key_mgmt=WPA-PSK
}

我寫了這段代碼,但它只能在文件末尾添加一個新行,僅用於 ssid(類似於 ssid=KB150):

if __name__ == '__main__':
    ssid = "KB150"
    password = "testpass"
    with open("example.txt", 'r+') as outfile:
        for line in outfile:
            if line.startswith("ssid"):
                sd = line.split("= ")
                outfile.write(line.replace(sd[1], ssid))
            if line.startswith("password"):
                pw = line.split("= ")
                line.replace(pw[1], password)
                outfile.write(line.replace(pw[1], ssid))

    outfile.close()

每當用戶在我的程序中輸入輸入時,ssid 和 psk 的值都會發生變化,因此我需要找到以這些關鍵字開頭的行並更改它們的值。

由於文件很小,您可以完全讀取它,進行替換並回寫。 您不必像with它那樣顯式地關閉它。

if __name__ == '__main__':
    ssid = "KB150"
    password = "testpass"
    # open for reading
    with open("example.txt", 'r') as infile:
        content = infile.read()
    # reopen it for writing
    with open("example.txt", 'w') as outfile:
        content = content.replace("WIFI_SSID", ssid).replace("WIFI_PASSWORD", password)
        outfile.write(content)

讀取時修改文件很棘手。 在這里討論

編輯

有多種方法可以處理它。 您可以保留包含內容的模板文件。

network={

      ssid="WIFI_SSID"
      scan_ssid=1
      psk="WIFI_PASSWORD"
      key_mgmt=WPA-PSK
}

該腳本可以讀取模板文件的內容,替換 ssid 和密碼並寫入目標文件。

另一種方法是使用正則表達式替換

import re
if __name__ == '__main__':
    ssid = "KB150"
    password = "testpass"

    with open("example.txt", 'r') as infile:
        content = infile.read()

    # reopen it for writing
    with open("example.txt", 'w') as outfile:
        content = re.sub('ssid="[^"]*"', f'ssid="{ssid}"', content)
        content = re.sub('psk="[^"]*"', f'psk="{password}"', content)
        outfile.write(content)

我猜你的line.startswith("ssid")沒有返回 True,因為在你的 example.txt 中是“ssid”之前的空格。 因此,您可能想要考慮使用正確數量的空格分割行或在每一行中搜索 ssid。

感謝 Shanavas M(在我的腦海里有他有用的提示),我的朋友幫助了我,我終於得到了我想要的東西:)

fileName = 'example.txt'
    result = ""
    ssid = "KB150"
    password = "testpass"

    with open(fileName, 'r') as filehandle:
        for line in filehandle:
            temp = line.split('=')[0]
            if temp == "ssid ":
                result += 'ssid = "{}"\n'.format(ssid)
            elif temp == 'password ':
                result += 'password = "{}"\n'.format(password)
            else:
                result += line

    with open(fileName, 'w') as filehandle:
        filehandle.write(result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM