[英]Python - efficient way to write to a file text?
I'm writing to a text file but it's not work properly as I expected. 我正在写一个文本文件,但是没有按预期工作。
Here's what I have: 这是我所拥有的:
#!/usr/lib/env python
import re
file = open("address.txt","r")
content = file.read()
file.close()
content = content.split('LAN ')[1:]
dic = {}
for lan in content:
dic[int(lan[0])] = lan[1:]
def address(lan_index):
address = re.findall('address\s(.*?)\s',dic[lan_index] )
if len(address) > 0:
print 'LAN', lan_index, ":", address[0]
else:
print 'No Address Found!'
return address[0]
ad1 = str(address(1))
new_ad = ad1
var1 = 'ad1'
filedata = None
with open('address.txt', 'r') as file :
filedata = file.read()
filedata = filedata.replace(ad1 , var1)
with open('address.txt', 'w') as file:
file.write(filedata)
here's my text file: 这是我的文本文件:
#line addresses LAN 1
address 192.168.6.6
network 192.168.6.6
my problem is when I want to replace ad1
for var1
it wont replace only my address
only it will replace network
as well as they have the same IP. 我的问题是,当我想将ad1
替换为var1
它不会仅替换我的address
,只会替换network
以及它们具有相同的IP。
My output is something like this: 我的输出是这样的:
address ad1 地址ad1
network ad1 网络广告1
Is there an efficient and possible way to avoid this and get something like this: 有没有一种有效且可能的方法来避免这种情况并得到类似的结果:
address ad1 地址ad1
network 192.168.6.6 网络192.168.6.6
I would be very grateful if that's possible. 如果可以的话,我将不胜感激。 Thank you 谢谢
Both your address are being replaced because filedata.replace(ad1 , var1)
is greedy. 因为filedata.replace(ad1 , var1)
贪婪filedata.replace(ad1 , var1)
所以您的两个地址都将被替换。 You can limit it by giving it the optional third argument: filedata.replace(ad1 , var1, 1)
telling it to make at most 1
replacements, or you could expand your capture group: '(address\\s.*?)\\s'
to include "address", and make var1 = "address ad1"
so that filedata.replace
only finds the lines that have "address" in them 您可以通过给它一个可选的第三个参数来限制它: filedata.replace(ad1 , var1, 1)
告诉它最多进行1
替换,或者您可以扩展捕获组: '(address\\s.*?)\\s'
包含“地址”,并使var1 = "address ad1"
以便filedata.replace
仅查找其中包含“地址”的行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.