Python 2.7路径替换字符串

时间:2019-04-14 22:16:21

标签: python string python-2.7 replace pathlib

我需要用其他字符串替换一些字符串。我正在使用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'

例如,我需要在配置站和/或配置设备中更改字符串,例如“ disabled”,“ hidden”,“ ssid”,“ key”。现在我正在使用这段代码

    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,我也想简化代码,因为我需要对许多其他字符串执行此操作。

有人有主意吗?

谢谢

1 个答案:

答案 0 :(得分: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'
   .....