[英]Python search for string in line
我有以下代码,我认为应该可以,但是似乎不行:
old_name = 'Some User'
new_name = 'New User'
with open(complete_filename, 'r') as provisioning_file:
lines = provisioning_file.read()
# if the old_name is in this file
if old_name in lines:
file_found = 1
with open(complete_filename + '.new', 'w') as new_provisioning_file:
for line in lines:
line = line.replace(old_name, new_name)
new_provisioning_file.write(line)
# provisioning_file.write(re.sub(old_name, new_name, line))
文件complete_filename
将是各种配置文件,我一直在测试XML文件的选择,下面是其中之一的示例代码片段:
<reg reg.1.address="1234" reg.1.label="Some User" >
<reg.1.auth reg.1.auth.password="XXXXXXXXXX" reg.1.auth.userId="1234" />
<reg.1.outboundProxy reg.1.outboundProxy.address="sip.example.com" />
<reg.1.server reg.1.server.1.address="sip.example.com" reg.1.server.1.expires="300" reg.1.server.2.expires="300" />
<reg.1.serverFeatureControl reg.1.serverFeatureControl.dnd="0" />
</reg>
该代码找到old_name
字符串并进入if
语句,然后打开complete_filename.new
进行写入,但是显然它从未在各行中找到该旧名称,而是按原样输出文件(即,它不会用new_name
代替old_name
) 。
从代码中可以看出,我还对re.sub进行了实验,结果相似。 我想念什么?
lines = provisioning_file.read()
这在我看来不对。 read()
不返回行列表,而是返回单个字符串。 因此,稍后for line in lines:
,不是逐行迭代,而是一次迭代一个字符。
遍历之前,请尝试split
对象。 我还建议更改其名称,以便更好地描述其内容。
with open(complete_filename, 'r') as provisioning_file:
text= provisioning_file.read()
# if the old_name is in this file
if old_name in text:
file_found = 1
with open(complete_filename + '.new', 'w') as new_provisioning_file:
for line in text.split("\n"):
line = line.replace(old_name, new_name)
new_provisioning_file.write(line + "\n")
编辑:替代方法:
old_name = 'Some User'
new_name = 'New User'
with open(complete_filename, 'r') as provisioning_file:
lines = provisioning_file.readlines()
# if the old_name is in this file
if any(old_name in line for line in lines):
file_found = 1
with open(complete_filename + '.new', 'w') as new_provisioning_file:
for line in lines:
line = line.replace(old_name, new_name)
new_provisioning_file.write(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.