Exercise of python notes - regular matching characters to create a file and write

'''
Create a file with matching characters and write
'''

import codecs
import them
import re
# (upstream)\s+(\S+)\s+([^}]+)}
file = "ga10.wms5.jd.com.txt"
name = "upstream"
'''
match upstream
reg = re.compile(r"(upstream)\s+(\S+)\s+([^}]+)}")
text= reg.findall()
print(text)
(upstream)\s+(\S+)\s+([^}]+)}
^(upstream)\s+(\S+)\s+{[^}]+}  -- no
\s*(upstream\s+(\S+)\s+{[^}]+})
'''
# ([^}]+) does not start with }
with codecs.open(file) as f:
    # reg = re.compile(r"")
    reg = re.compile(r"\s*(upstream\s+(\S+)\s+{[^}]+})")
    text= reg.findall(f.read())
    if not os.path.exists(name): # Create when the directory does not exist
        os.mkdir(name)
    os.chdir(name)
    for i in text:
        with codecs.open(i[1],"w") as fw:
            fw.write(i[0])
    os.chdir("..")
'''
match location
(location\s+/(\S+)/\s+{\s+proxy_next_upstream.*?[^}]*?})
'''
loca = "location"
reLo = re.compile(r"(location\s+/(\S+)/\s+{\s+proxy_next_upstream.*?[^}]*?})")
with codecs.open(file) as fl:
    textLo = reLo.findall(fl.read())
    if not os.path.exists(loca):
        os.mkdir(local)
    os.chdir(local)
    for each in textLo:
        ff = each[1] + ".location.conf"
        with codecs.open(ff,"w") as flw:
            flw.write(each[0])
    os.chdir("..")

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325336173&siteId=291194637