【发布时间】:2019-09-04 22:10:09
【问题描述】:
我需要用其他字符串替换一些字符串。我正在使用函数 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'
config 'client' 部分中的 option disabled 行,我的程序一直添加另一个 0 我也想减轻我的代码,因为我需要为许多其他字符串这样做。
有人有想法吗?
谢谢
【问题讨论】:
-
您能否澄清一下:pathlib 模块是 Python 3.4 中的新模块,并且您的标题中有 Python 2.7。你使用的是什么版本的 Python?你在使用路径库吗?什么是路径?它只是一个字符串,你根本没有使用 pathlib 吗?
-
不要将 cmets 添加到您自己的问题中;编辑您的问题以澄清。正如目前在您的 cmets 中所述,路径是一个
Path()对象,但在问题中,您使用两个参数调用path.replace(),而Path.replace()只允许一个参数。请提供明确的minimal reproducible example。
标签: python string python-2.7 replace pathlib