[Python] Insert replace text based on a name in other file python script

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    I have two text files, File 1 is a list of names of meshes with a path sometimes the name is the same as the path name and can contain numbers.

    I need is to insert File 1 filename/path onto every matching StaticMesh=StaticMesh'Dog' line based on its 'name'

    File 2 is blocks of data I need to change certain lines. The lines always have StaticMesh=StaticMesh'REPLACEWORD'

    I have a python script but I get another error. also I would like to write to a file

    Traceback (most recent call last):
    File "C:\Users\TUFGAMING\Desktop\python\main.py", line 32, in <module>
    main()
    File "C:\Users\TUFGAMING\Desktop\python\main.py", line 20, in main
    quoted_word = match.group(1)
    AttributeError: 'NoneType' object has no attribute 'group'


    Here is a sample of the a block of data

    (File 1)

    Dog /Game/Meshes/Bulldog

    Fish /Game/Meshes/Goldfish

    Cat /Game/Meshes/Cat


    (File 2)

    Begin Map
    Begin Level

    Begin Map
    Begin Level
    Begin Actor Class=StaticMeshActor Name=Dog Archetype=StaticMeshActor'/Script/Engine.Default__StaticMeshActor'
    Begin Object Class=StaticMeshComponent Name=StaticMeshComponent0 ObjName=StaticMeshComponent0 Archetype=StaticMeshComponent'/Script/Engine.Default__StaticMeshActor:StaticMeshComponent0'
    End Object
    Begin Object Name=StaticMeshComponent0
    StaticMesh=StaticMesh'Dog.Dog'
    RelativeLocation=(X=-80703.9,Y=-91867.0,Z=7863.95)
    RelativeScale3D=(X=1.0,Y=1.0,Z=1.0)
    RelativeRotation=(Pitch=0.0,Yaw=-169.023,Roll=0.0)
    End Object
    StaticMeshComponent='StaticMeshComponent0'
    RootComponent='StaticMeshComponent0'
    ActorLabel="Dog"
    End Actor
    End Level
    Begin Surface
    End Surface
    End Map


    (Result)

    StaticMesh=StaticMesh'/Game/Meshes/Bulldog'

    StaticMesh=StaticMesh'/Game/Meshes/Goldfish'

    StaticMesh=StaticMesh'/Game/Meshes/Cat'


    import re


    def main():
    file_one = 'file-1.txt'
    file_two = 'file-2.txt'

    # holds (firstword, secondline)
    word_tuples = []

    with open(file_one, 'r') as file:
    for line in file:
    words = line.split() # splits on white space
    word_tuples.append((words[0], words[1]))

    with open(file_two, 'r') as file:
    for line in file:
    # extract content between the single quotes
    match = re.search(r"StaticMesh=?'(.+)'", line)
    quoted_word = match.group(1)

    # see if any of the lines from file 1 match it
    for word_tuple in word_tuples:
    if word_tuple[0] == quoted_word:
    print("MATCH FOUND")
    print(f"file1: {word_tuple[0]} {word_tuple[1]}")
    print(f"file2: {line.strip()}")
    print(f"file3: {line}".replace(quoted_word, word_tuple[1]))


    if __name__ == '__main__':
    main()

    Continue reading...

Compartilhe esta Página