Skip to main content
 首页 » 编程设计

python之从文本文件中检索随机预格式化的文本

2025年05月04日7jyk

我正在编写一个 python 脚本来获取格式为 StartTime="mm/dd/yyyy hh:mm:ss:ccc" 和 EndTime="mm/dd/yyyy hh:mm:ss:ccc" 位于文本文件中。

所以我继续搜索 StartTime 和 Endtime 但我怎样才能得到 (="mm/dd/yyyy hh:mm:ss: ccc") ?当我得到 StartTime 和 EndTime 字符串时,我想使用函数 saveIntoFile(File, textToSave) 将它们保存在另一个文本文件中,但我认为我将能够自己处理这部分。

def getTimeCode(File) : 
    fopen = open(File, 'r')     
    text = fopen.read() 
    for t in text : 
        if t == "StartTime" : 
            #what should I do now ? 
        if t == "EndTime" : 
            #what should I do now ? 
 
def saveIntoFile(filename, textToSave): 

请您参考如下方法:

import re 
 
def getTimeCode(fn): 
    with open(fn, 'r') as f: 
        for line in f: 
            m = re.search(r'(\w)="(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d:\d\d\d)"', line) 
            if m: 
                if m.group(1) == 'StartTime': 
                    # do something with m.group(2) 
                elif m.group(1) == 'EndTime': 
                    # do something with m.group(2) 
                else: 
                    # m.group(1) unknown