簡體   English   中英

Python 2.7路徑替換字符串

[英]Python 2.7 path replace string

我需要用別人替換一些字符串。 我正在使用函數pathlib這樣做它工作正常但我有一個問題,當我的文件中有兩個相同的字符串,我需要只更改一個

我的文件(wireless.temp)就像這個例子

config 'conf'
    option disabled '0'
    option hidden '1'
    option ssid 'confSSID'
    option encryption 'psk2'
    option key 'qwerty'

config 'client'
    option disabled '0'
    option hidden '0'
    option ssid 'clientSSID'
    option encryption 'psk2'
    option key 'qwerty'

例如,我需要在配置工作站和/或配置設備中更改“禁用”,“隱藏”,“ssid”,“密鑰”等字符串。 現在我正在使用這段代碼

    f1=open('wireless.temp', 'r').read()
    f2=open('wireless.temp','w')

    #checkbox from QT interface
    if self.chkWifiEnable.isChecked():
        newWifiEnable = "0"
    else:
        newWifiEnable = "1"

    start = f1.find("config 'client'")
    print start
    end = f1.find("config", start + 1)
    print end
    if end < 0:
        end = len(f1)
    station = f1[start:end]
    print station
    print f1.find("disabled")
    print f1.find("'")
    actualValue = f1[(station.find("disabled")+10):station.find("'")]
    print actualValue
    station = station.replace("disabled '" + actualValue, "disabled '" + newWifiEnable)
    print station
    m = f1[:start] + station + f1[end:]
    f2.write(m)

這個代碼有問題,首先是我執行輸出時

config 'conf'
    option device 'radio0'
    option ifname 'conf'
    option network 'conf'
    option mode 'ap'
    option disabled '0'
    option hidden '1'
    option isolate '1'
    option ssid 'Conf-2640'
    option encryption 'psk2'
    option key '12345678'

config 'client'
    option device 'radio0'
    option ifname 'ra0'
    option network 'lan'
    option mode 'ap'
    option disabled '00'    <---- problem
    option hidden '0'
    option ssid 'FW-2640'
    option encryption 'psk2'
    option key '12345678'

配置'客戶端'部分中的選項禁用行,我的程序另外添加0我也想減輕我的代碼,因為我需要為許多其他字符串執行此操作。

有沒有人有想法?

謝謝

Pathpathlib2是一個紅鯡魚。 您正在使用它來查找並將文件讀入字符串。 問題是在整個文本的一小部分中替換文本。 具體來說,在'config device'和下一個'config ...'項之間

您可以使用.find()來查找正確的config部分的開頭,並再次找到下一個config部分的開頭。 確保將-1 (未找到)視為該部分的結尾。 可以修改該范圍內的文本,然后將生成的修改與之前和之后的未修改部分組合在一起。

wirelessF = """
config device
   .....
   option key 'qwerty'
   .....
config station
   .....
   option key 'qwerty'
   .....
config otherthing
   .....
   option key 'qwerty'
   .....
"""

actualWifiPass = 'qwerty'
newWifiPass = 's3cr3t'

start = wirelessF.find("config station")
end = wirelessF.find("config ", start+1)
if end < 0:
   end = len(wirelessF)
station = wirelessF[start:end]
station = station.replace("key '"+actualWifiPass, "key '"+newWifiPass)
wirelessF = wirelessF[:start] + station + wirelessF[end:]

print(wirelessF)

輸出:

config device
   .....
   option key 'qwerty'
   .....
config station
   .....
   option key 's3cr3t'
   .....
config otherthing
   .....
   option key 'qwerty'
   .....

暫無
暫無

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

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