chowpay chowpay - 24 days ago 6
Python Question

How to parse a concatenated a zone file

I have a large zone file that I want to move to another provider. My issue is the export is only one large concatenated zone file where as my new registrar only accepts single standard zone files.

For example allzone.txt contains:

somedomain.com
=========
Record data...
...
------------
anotherdomain.com
=========
Record data...
...
------------
evenmoredomain.com
=========
Record data...
...
------------


What I'd like to happen is that it takes the one file above and creates 3 files.

somedomain.txt
anotherdomain.com.txt
evenmoredomain.com.txt


Inside each of the files the delimiters of :

anydomain.com
=========
and
------------


are removed only leaving

"Record data"


Between.

So a file should be named domainA.com.txt and inside just the corresponding record data.

Not sure what the best way to do this. I can split on a delimiter but not sure how to take that content to write a new file where the name is what is before the delimiter (anydomain.com)

Thanks!

Answer

More or less

current_file = None

with open('allzone.txt') as f:

    # read line by line
    for line in f:

        # open next file and close previous
        if line.startswith('domain'):
            # close previous file
            if current_file:
                current_file.close()
            # open new file
            current_file = open(line.strip() + '.txt', 'w')

        # write to current file
        if current_file:
            if not (line.startswith('domain') or line.startswith('---') or line.startswith('===')):
                current_file.write(line)

    # close last file
    if current_file:
        current_file.close()

EDIT: new version for any domain

current_file = None

with open('allzone.txt') as f:

    # read line by line
    for line in f:

        # open next file
        if not current_file:
            # open new file
            current_file = open(line.strip() + '.txt', 'w')
            # skip next line 
            next(f) 
        else:
            # close previous file
            if line.startswith('---') :
                current_file.close()
                current_file = None
            # write records    
            #elif not line.startswith('==='): # use it if you don't use `next(f)` 
            else:
                current_file.write(line)

    # close last file
    if current_file:
        current_file.close()