从fi有效读取主要版本号

2024-10-02 12:29:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个脚本,通过读取文件来检查主版本

在任何一行存储版本号主次修正你知道吗

像这样:

VERSION = 23.5.1

所以读这个数字23我是这样做的

filePath = os.path.join(os.getcwd(), 'Makefile')
with open(filePath, 'r') as mkfh:
    for line in mkfh:
        if line.startswith('VERSION'):
            print line.replace(' ','').split('=')[-1].split('.')[0]
            break

他们获得主版本的方法是否比使用replace和split两次更有效?你知道吗


Tags: 文件path版本脚本osversion版本号line
3条回答

你不需要使用replace

print line.split('=')[-1].split('.')[0].strip()

lstrip更合适。你知道吗

print line.split('=')[-1].split('.')[0].lstrip()

使用正则表达式:

import re

pattern = re.compile(r'VERSION\s*=\s*(\d+)')  # \s: space, \d: digits

with open('Makefile') as mkfh:
    for line in mkfh:
        matched = pattern.match(line)
        if matched:
            print matched.group(1)
            break

顺便说一句,如果要访问当前工作目录中的文件,则不需要使用os.path.join。你知道吗

我会做line.split(' = ')[1].split('.')[0],但除此之外,我觉得还可以。有些人可能会使用regex解决方案,比如re.search(r'VERSION = (\d+)', line).group(1)。你知道吗

相关问题 更多 >

    热门问题