python读写文件里的某个特定字符串

前言

在写自动打包sdk脚本时,需要读取文件文件里的内容,对版本号根据sdk里的内容进行替换

参考:
python读写更新替换文件内容
用python替换文件中内容的两种方法
python 字符串前面加r,u的含义
python调用其他文件的类和函数
vscode 写 python 脚本设置不自动排序
python在终端输出不同颜色的打印,自定义日志和自定义log输出级别

一开始使用了一个比较笨的方法,遍历文件进行比较读取,后面发现可以使用os.popen读取,两种读取方法如下
读取文件api:open(路径)readlines()os.popen(命令).read()
字符串操作api:formatsplitstripreplace
管道过滤包含:grep xxx
管道过滤不包含:grep -v xxx
字符串包含: xx in xxxx
字符串不包含: xx not in xxxx

# encoding:utf-8
import os
#读取文件
import fileinput
import sys
import time

def main():
 T1 = time.time()
 T2 = time.time()
 showTime(T1, T2)

# 遍历循环每一行进行读取
def readSpecVersion():
    spec_path = 'xxx/xxx.spec'
    spec_lines = open(spec_path).readlines()
    old_version = ''
    for s in spec_lines:

            if ('s.version' in s) and (s.version.to_s not in s):
            # 取等号右侧的内容
                old_version = s.split('=', 1)[1]
            # 去掉空格、去掉单引号、去掉换行符,然后就是版本号文本了
                old_version = .replace('"', '').replace("'", '').replace('\n', '').strip()

    print('old_version: ',old_version)

# 使用os.popen读取,可以一行就写完
def readSpecVersion2():
    spec_path = 'xxx/xxx.spec'
    old_version = os.popen('cat {path} | grep s.version | grep -v s.version.to_s'.format(
        path=spec_path)).read().split('=', 1)[1].replace('"', '').replace("'", '').replace('\n', '').strip()
    return old_version

#使用fileinput+sys.stdout.write写
def readAndRightSpec():
    path = 'xxx/xxx.spec'
    # 读取满足条件的行
    oldLine = os.popen('cat {path} | grep s.version | grep -v s.version.to_s'.format(
        path=path)).read()
    oldVersion = oldLine.split('=', 1)[1].replace(
        '"', '').replace("'", '').replace('\n', '').strip()
    # 替换对应的内容
    newVersion = '1.2.3.456'
    newLine = oldLine.replace(oldVersion, newVersion)
    # 将修改放入到文件里
    for line in fileinput.input(path, inplace=1):
        if oldLine in line:
            #print(newLine, end="")
            sys.stdout.write(newLine)
        else:
            #print(line, end="")
            sys.stdout.write(line)

def showTime(T1, T2):
    totalMS = (T2 - T1)*1000
    print('程序运行时间{tms:.3f}毫秒'.format(tms=totalMS))
    dd = 10000
    td = long(totalMS*dd)
    tm = td/(60*1000*dd)
    td = td - (tm*60*1000*dd)
    ts = td/(1000*dd)
    tms = float((td - (ts*1000*dd)))/dd
    print('程序运行时间{tm}分 {ts}秒 {tms:.3f}毫秒'.format(tm=tm, ts=ts, td=td, tms=tms))

main()

Python获取当前用户的主目录路径

import os
 
print os.environ['HOME']
print os.path.expandvars('$HOME')
print os.path.expanduser('~')

一个完整的common.py

# encoding:utf-8
import os
import sys
import time
import fileinput

# 修改Podfile文件,path:路径,isAddUseFrameworks:是否要使用use_frameworks!


def log(message, type):
    '''基本描述

    打印日志

    :message 消息内容
    :type   s表示成功,e表示错误,i表示普通
    '''
    if type == 's':
        print("\033[1;32;40m{msg}\033[0m".format(msg=message))
    elif type == 'e':
        print("\033[1;31;40m{msg}\033[0m".format(msg=message))
    elif type == 'i':
        print(message)
    else:
        print(message)


def updatePofile(path, isAddUseFrameworks):
    '''基本描述

    更新Podfile文件的use_frameworks!选项小

    :path                 Podfile文件所在的路径
    :isAddUseFrameworks   是否要打开use_frameworks!
    '''
    podfile_path = os.path.abspath(os.path.join(
        path, 'Podfile'))
    oldLine = ''
    newLine = ''
    if isAddUseFrameworks:
        # 要打开注释
        oldLine = os.popen("cat {path} | grep 'use_frameworks!' | grep '#'".format(
            path=podfile_path)).read()
        if len(oldLine) == 0:
            log('=====不需要更新Podfile=====', 's')
            return
        newLine = oldLine.replace('#', '')
    else:
        # 要增加注释,不能使用
        oldLine = os.popen("cat {path} | grep 'use_frameworks!' | grep -v '#'".format(
            path=podfile_path)).read()
        if len(oldLine) == 0:
            log('=====不需要更新Podfile=====', 's')
            return
        newLine = oldLine.replace('use_frameworks!', '#use_frameworks!')

    print('oldLine: ', oldLine)
    print('newLine: ', newLine)
    # 将修改放入到文件里
    for line in fileinput.input(podfile_path, inplace=1):
        if oldLine in line:
            sys.stdout.write(newLine)
        else:
            sys.stdout.write(line)

    log('=====Podfile 修改完成=====', 's')

# 执行pod install


def podInstall(path):
    '''基本描述

    进入Podfile所在的路径并执行pod install
    :path                 Podfile文件所在的路径
    '''
    os.system('cd {podfilePath} && pod install'.format(
        podfilePath=path))

    log('=====pod install 修改完成=====', 's')


def showTime(startTime, endTime):
    '''基本描述

    统计代码执行执行时间,展示成xx分 xx秒 xx毫秒

    :startTime 开始计时的时间,以time.time()获取,*1000成毫秒为单位,time.time()*1000
    :endTime   结束计时的时间,以time.time()获取,*1000成毫秒为单位,time.time()*1000
    '''
    totalMS = (endTime - startTime) * 1000
    print('程序运行时间{tms:.3f}毫秒'.format(tms=totalMS))
    dd = 10000
    td = long(totalMS * dd)
    tm = td / (60 * 1000 * dd)
    td = td - (tm * 60 * 1000 * dd)
    ts = td / (1000 * dd)
    tms = float((td - (ts * 1000 * dd))) / dd
    log('程序运行时间{tm}分 {ts}秒 {tms:.3f}毫秒'.format(
        tm=tm, ts=ts, td=td, tms=tms), 's')


你可能感兴趣的:(python读写文件里的某个特定字符串)