Python动态修改文件内容

Python 动态修改文件内容

问题:
需要每次执行时创建新的执行日志,并且日志的版本号自动更新
解决思路:
动态修改脚本内容
code

# -*- coding: utf-8 -*-

import sys

__version__ = (1, 4, 0)

vs = '.'.join([str(i) for i in __version__])

log_file = open('log_{}.txt'.format(vs), 'w')
sys.stdout = log_file
desc = 'this is a desc for the execution'
print(desc)


def rewrite():
    v_num = 100 * __version__[0] + 10 * __version__[1] + __version__[2]
    v_num += 1
    v_str = str(v_num)
    new_v = (int(v_str[0]), int(v_str[1]), int(v_str[2]))
    new_v_str = str(new_v)
    tmp = open(__file__, 'r+')
    lines = tmp.readlines()
    for l in lines:
        if '__version__' in l:
            i = lines.index(l)
            lines[i] = '__version__ = {}\n'.format(new_v_str)
            break
    tmp.seek(0)
    tmp.writelines(lines)
    tmp.close()


rewrite()

if __name__ == '__main__':
    pass

你可能感兴趣的:(Python)