有效地从文件

时间:2015-08-01 05:25:24

标签: python list slice

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

在任何一行都存储版本号Major.Minor.Fix

像这样:

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两次的更有效方法吗?

4 个答案:

答案 0 :(得分:1)

您不能使用replace

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

lstrip会更合适。

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

答案 1 :(得分:1)

使用正则表达式:

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

答案 2 :(得分:1)

我会line.split(' = ')[1].split('.')[0],但除此之外我觉得好。有些人可能会使用正则表达式解决方案,例如re.search(r'VERSION = (\d+)', line).group(1)

答案 3 :(得分:0)

如果效率是目标,那么对于像makefile这样的东西,你应该一次性处理文件,而不是一次处理一行:

import os
import re

filePath = os.path.join(os.getcwd(), 'Makefile')
with open(filePath, 'rb') as mkfh:
    data = mkfh.read()

pattern = '^VERSION *= *(\d+)'
search = re.compile(pattern, re.MULTILINE).search

print(search(data).group(1))