根据python中的条件修改特定行

2024-09-30 16:41:47 发布

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

我正在为行替换编写python脚本。
基本上,我需要一些行,比如在“ObjectAlias Here”部分| bewteen“BeginKeyframe”和“EndKeyframe”|每个“default”下的前6行,不以“-”开头

我的文件的主要部分如下所示:

# ...
# BeginObject
# lines
# ObjectAlias XXX
# lines
# BeginKeyframe
#   -1.000 24 default
#   12 lines                # not here since "default" line starts with "-"
#   0.000 24 default
#   12 lines                # first 6 lines need to be modified
#   1.000 24 default
#   12 lines                # first 6 lines need to be modified
#   ...
# EndKeyframe
# lines
# EndObject
# {
# next object YYY section
# }
# ...

这是我现在的代码,它只在第一个“default”下成功,没有startswith“-”,我知道这是因为我将tag设置为False,但是我必须确保在每个“default”下只修改前6行。 我能用当前代码做什么?你知道吗

def update(fileobj, objlist):
    fileobj.seek(0)
    tmpscene = ""
    tag = False
    count = 0
    obj = None
    for line in fileobj:
        if tag and count < 6:
            offset = t_objdict[obj].split(",")[count]
            mod = "  " + convert(line, offset) + line.split(None, 1)[-1]
            tmpscene += mod
            count += 1
            if count > 5:
                tag = False     # Here is my problem!
            continue
        tmpscene += line
        if "ObjectAlias" in line:
            for obj in objlist:
                if "ObjectAlias " + obj + "\n" in line:
                    for line in fileobj:
                        tmpscene += line
                        if line.strip().endswith("default") and not line.strip().startswith("-"):
                            tag = True
                            count = 0
                            break
                    break
    return tmpscene

**编辑:**重写我的代码,仍然无法正常工作。你知道吗


Tags: 代码infalseobjdefaultforifhere