Link_tester
Link_tester

Reputation: 1081

how to add a text dynamically to several files in python

I have several files and want to add some text to them (named as changed_1, changed_2, changed_3 and so on) in python. This is some lines of my files (but my files have thousands of rows):

$MeshFormat
2.2 0 8
$EndMeshFormat
$PhysicalNames
8
2 12 "back"
2 14 "Fault"
3 1 "volume_1"
$EndPhysicalNames
...

I want to add line/s exactly after the 8th line (3 1 "volume_1"). These lines should be also generated dynamically. I have another variable named as n_iteration. If n_iteration is 2, I want to add 3 2 "volume_2" exactly after the 8th line. If it is 3, I want to add 3 2 "volume_2" and 3 3 "volume_3" and so on. Finally I want to have my files changed and saved exactly like the input format but with this added lines (let's say n_iteration = 4):

$MeshFormat
2.2 0 8
$EndMeshFormat
$PhysicalNames
8
2 12 "back"
2 14 "Fault"
3 1 "volume_1"
3 2 "volume_2"
3 3 "volume_3"
3 4 "volume_4"
$EndPhysicalNames
...

I could only import all my files and sort them with the following code, but I was not successful in doing what I explained:

from glob import glob
all_files = glob('changed_*')
for i in all_files:
    with open(str(i)) as lines:
...

In advance, I appreciate any help and feedback.

Upvotes: 0

Views: 769

Answers (2)

Alexander Riedel
Alexander Riedel

Reputation: 1359

This is basically the code to @Bens comment, except that i doesn't count until the eigth line when writing, but inserts the stuff you want to add to the read list and then writes everything to a file

with open("test.txt", "r") as f:
    data = f.readlines()


n_iteration = 2

for i in range(n_iteration,0,-1):
    data.insert(7, ('3 ' + str(i) +' "volume_' + str(i) + '"\n'))

with open("test_new.txt", "w") as f:
    for c in data:
        f.write(c)

Upvotes: 1

Ben
Ben

Reputation: 5087

You need to understand the difference between a file and its contents. You need to understand how to read in the contents of a file, and what can and cannot be done in writing to a file. In general, you can write to the end of a file, and you can write over a file, but you cannot insert into a file. You can create the effect of inserting by reading in the contents of the file, and writing it back out with the new content added in.

One approach: you read in the file line by line, so that you have a list of the lines. If you're always inserting your new data after the eighth line, you can now write out the contents one by one, then after you have written out the eighth line, write out your new data, then continue with the rest of the contents you read in at the start.

Upvotes: 2

Related Questions