如何使用 python 将增量版本号保存在文件中?

How to save the increment version number in file using python?

我正在尝试将 ElasticSearch 的版本保存在一个文件中。

输入文件:

ElasticSearch 5:1:

第一次执行后的输出文件

ElasticSearch 5:1:0

第二次执行后的输出文件

ElasticSearch 5:1:1
ElasticSearch 5:1:0

第三次执行后的输出文件

ElasticSearch 5:1:2
ElasticSearch 5:1:1
ElasticSearch 5:1:0

我的代码如下

import re
reg = r'(?:)$'
with open('elastic.txt', 'r') as fread:
    data = fread.read()
    with open('elastic.txt', 'a') as fwrite:
        fwrite.seek(0,0)
        fwrite.write(re.sub(reg, lambda x: str(int(x.group(0)) + 1), data, 1, re.M))

我面临的两个问题 seek(0,0) 无法正常运行并且正则表达式未添加

您可以使用

import re
reg = r'\A(.*:)(\d*)$'
with open('elastic.txt', 'r') as fread:
    data = fread.read()
    with open('elastic.txt', 'w') as fwrite:
        fwrite.write(re.sub(reg, lambda x: "{}{}\n{}".format(x.group(1), str(int(x.group(2)) + 1), x.group()) if len(x.group(2)) else "{}0".format(x.group(1)) , data, 1, re.M))

详情

  • \A(.*:)(\d*)$ - 一个正则表达式,如果它有 :,则获取文件开头的行,并将 : 之前的部分捕获到第 1 组,并捕获任何零或更多数字进入第 2 组(在行尾)
  • data是整个文件内容
  • lambda x: "{}{}\n{}".format(x.group(1), str(int(x.group(2)) + 1), x.group()) if len(x.group(2)) else "{}0".format(x.group(1)) 替换为第 1 组,递增的第 2 组和换行符 + 整个第一行 如果 第 2 组包含数字,否则,它添加 0 到第一行而不加倍。

带有自定义 incr_patch_version 函数的扩展解决方案:

import re

regex = r'(?<=:)\d*$'


def incr_patch_version(fname):
    with open(fname, 'r+') as f:
        lines = f.readlines()
        new_line = re.sub(regex, lambda x: str(int(x.group()) + 1 if x.group().isnumeric() else 0), lines[0])
        f.seek(0)
        f.write(new_line) if lines[0].strip().endswith(':') else f.writelines([new_line, *lines])


fname = 'elastic.txt'

incr_patch_version(fname)
incr_patch_version(fname)
incr_patch_version(fname)
incr_patch_version(fname)

最终elastic.txt内容:

ElasticSearch 5:1:3
ElasticSearch 5:1:2
ElasticSearch 5:1:1
ElasticSearch 5:1:0