Skip to content
Advertisement

Writing a text file, using parts of other text files

I need to figure out something that is confusing me, hope someone can help. I have two text files with different information (these actually input files to run on Abaqus, but let’s call them .txt)

  • MAIN.txt
filler line 1
filler line 2
filler line 3
*material,name=A
density = 9
0,0
0,0
0,0
0,0
**-------------------------------------- 
FILLER LINE 5
FILLER LINE 6
FILLER LINE 7

and

  • SUB.txt
*material,name=A
density = 10
1,1
1,1
1,1
1,1
**--------------------------------------

I guess it is obvious what I want to do, write a script that creates a NEWFILE.txt which substitutes from the SUB.txt to MAIN.txt so that my NEWFILE.txt would look like this

*filler line 1
filler line 2
filler line 3
***material,name=A
density = 10
1,1
1,1
1,1
1,1
**--------------------------------------**
FILLER LINE 5
FILLER LINE 6
FILLER LINE 7*

This is the code I have come up with, I have no issues creating a new text file, but I am unable to figure out how to swap that bit of text, from SUB.txt to the NEW.txt

mainFile = 'main.txt'
subFile = 'sub.txt'
outputFile = 'new.txt'
marker1 = '*material,name=A'
marker2 = '**--------------------------------------'


with open(mainFile, 'r') as f1, open(subFile, 'r') as f2, open(outputFile, 'w') as f3:
    for line in f1:
        for line2 in f2:
            if line != marker1:
                f3.write(line)
            else ?

Advertisement

Answer

You read the whole file MAIN.txt into a string, the whole file SUB.txt into another. Then, find the positions of marker1 and marker2 in the main string, and substitute everything inbetween.

mainFile = 'main.txt'
subFile = 'sub.txt'
outputFile = 'new.txt'
marker1 = '*material,name=A'
marker2 = '**--------------------------------------'

with open(mainFile, 'r') as f1, open(subFile, 'r') as f2, open(outputFile, 'w') as f3:
    main = f1.read()
    sub = f2.read()
    
    start = main.find(marker1)
    end = main.find(marker2) + len(marker2)
    
    main = main[:start + 1] + sub + main[end:]
    f3.write(main)

Done !

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement