Python 高效地从文件中读取主要版本号
我正在编写一个脚本,通过读取文件来检查主版本 在任何一行存储版本号Major.Minor.Fix 像这样:Python 高效地从文件中读取主要版本号,python,list,slice,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'): prin
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
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]
,但除此之外,我觉得还可以。有些人可能会使用正则表达式解决方案,如re.search(r'VERSION=(\d+),line.group(1)
如果效率是目标,那么对于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))