简体   繁体   中英

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.

My output is something like this:

address ad1

network ad1

Is there an efficient and possible way to avoid this and get something like this:

address ad1

network 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM