如何解析连接的区域文件

How to parse a concatenated a zone file

我有一个大型区域文件,我想将其移至其他提供商。我的问题是导出的只是一个大型串联区域文件,而我的新注册商只接受单个标准区域文件。

例如allzone.txt包含:

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

我想要发生的是它采用上面的一个文件并创建 3 个文件。

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

在每个文件中,分隔符为:

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

被删除只留下

"Record data"

之间。

所以一个文件应该命名为domainA.com.txt并且里面只有相应的记录数据。

不确定最好的方法是什么。我可以在分隔符上拆分,但不确定如何使用该内容来编写一个新文件,其中名称是分隔符之前的名称 (anydomain.com)

谢谢!

也许这样的事情会奏效?它可能还需要一些调整

def main():
    with open('allzone.txt', 'r+') as f:
        data = ''
        first_line = ''
        for line in f:
            if first_line == '':
                first_line = line
            elif line == '------------\n':
                new_file = open('%s.txt' % first_line.rstrip(), 'w+')
                new_file.write(data)
                new_file.close()
                first_line = ''
                data = ''
            elif line == '=========\n' or line == '...\n' or line == '------------\n':
                pass
            else:
                data += line


if __name__ == '__main__':
    main()

差不多

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()

编辑:任何域的新版本

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()