今天在看pygments的代码的时候,发现有一个类是 自生成式的 就是在main方法里面 通过一系列操作写文件
当然 这个文件就是他自己了
其中的代码片段
""" pygments.lexers._mapping ~~~~~~~~~~~~~~~~~~~~~~~~ Lexer mapping defintions. This file is generated by itself. Everytime you change something on a builtin lexer defintion, run this script from the lexers folder to update it. Do not alter the LEXERS dictionary by hand. :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ LEXERS = { 'ABAPLexer': ('pygments.lexers.other', 'ABAP', ('abap',), ('*.abap',), ('text/x-abap',)), } if __name__ == '__main__': import sys import os # lookup lexers found_lexers = [] sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) for filename in os.listdir('.'): if filename.endswith('.py') and not filename.startswith('_'): module_name = 'pygments.lexers.%s' % filename[:-3] print module_name module = __import__(module_name, None, None, ['']) for lexer_name in module.__all__: lexer = getattr(module, lexer_name) found_lexers.append( '%r: %r' % (lexer_name, (module_name, lexer.name, tuple(lexer.aliases), tuple(lexer.filenames), tuple(lexer.mimetypes)))) # sort them, that should make the diff files for svn smaller found_lexers.sort() # extract useful sourcecode from this file f = open(__file__) try: content = f.read() finally: f.close() header = content[:content.find('LEXERS = {')] footer = content[content.find("if __name__ == '__main__':"):] # write new file f = open(__file__, 'w') f.write(header) f.write('LEXERS = {\n %s\n}\n\n' % ',\n '.join(found_lexers)) f.write(footer) f.close()
前面的是生成一个列表
关键是地方在
# extract useful sourcecode from this file f = open(__file__) try: content = f.read() finally: f.close() header = content[:content.find('LEXERS = {')] footer = content[content.find("if __name__ == '__main__':"):] # write new file f = open(__file__, 'w') f.write(header) f.write('LEXERS = {\n %s\n}\n\n' % ',\n '.join(found_lexers)) f.write(footer) f.close()
就是打开文件,然后依次写头部。写尾部。首先把文件读取出来。字符才转换成列表的形式
然后用find()的方法 找到要查找的串的第一个元素开始的位置。然后就是用列表的切片来截取了
有一个地方用了%r 格式化
经过我的测试 %r 和%s相比 %r会把回车换行这些转换成\n
这样写文件的话 就不会因为系统的差异而导致文件格式不一致 甚至出现问题了