0

I have several files and want to add some text to them (files are named as changed_1, changed_2, changed_3 and so on) in python. Here I copied a piece of my file:

$MeshFormat
2.2 0 8
3 1 "volume_1"
$EndPhysicalNames

I want to add line/s exactly after the 3rd line (3 1 "volume_1"). I have another variable named as n_iteration. If n_iteration is 2, I want to add 3 2 "volume_2" exactly after the 3rd 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 these added lines (let's say n_iteration = 4):

$MeshFormat
2.2 0 8
3 1 "volume_1"
3 2 "volume_2"
3 3 "volume_3"
3 4 "volume_4"
$EndPhysicalNames

Point is that I want to do the same (adding these lines) for several files. I tried the following code but I was not successful. Firstly, it is doing the iteration over n_iteration rather than my files (it is making 4 outputs rather than i ones). I have three inputs but it is making four outputs which all are resulted from the last file (last i from the first for loop). It has also a problem for doing what I want (it adds new line differently in outputs):

from glob import glob
all_files = glob('changed_*')
for i in all_files:
    with open(i, "r") as f:
        data = f.readlines()
        n_iteration = 4
        for j in range(n_iteration,0,-1):
            with open('new'+ str (j), "w") as f:
                data.insert(2, ('3 ' + str(j) +' "volume_' + str(j) + '"\n'))
                del data[2+n_iteration]
                for c in data:
                    f.write(c)

In advance, I do appreciate any help.

4
  • can you show us what the file looks like after the script runs Commented Nov 3, 2020 at 14:44
  • dear @Avi Baruch, files are .msh files and only contain simple text. But they have thousands of rows. I only showed here first four lines. Commented Nov 3, 2020 at 14:48
  • thats fine, just show the affected lines after so I can see what wrong Commented Nov 3, 2020 at 14:51
  • I did it for three files and wanted to add four lines (n_iteration = 4). It gave me four files, which are all exported from the last file imported to algorithm in the first for loop. the first file is completely OK. Second one= $MeshFormat 2.2 0 8 3 2 "volume_2" 3 3 "volume_3" 3 4 "volume_4" 3 1 "volume_1". Third one= $MeshFormat 2.2 0 8 3 3 "volume_3" 3 4 "volume_4" 3 1 "volume_1". Fourth one = $MeshFormat 2.2 0 8 3 4 "volume_4" 3 1 "volume_1". So, I have four outputs rather than three ones and also they are wrong. Commented Nov 3, 2020 at 14:57

1 Answer 1

1

Ok so a wide aproximation to your needs could be:

import re
from pathlib import Path


regex = re.compile(r'\d\s\d\s\"volume_\d\"') # X X "volume_N"

def process_files(folder_path, n_iteration):
    txt_folder = Path(folder_path).rglob('*.txt')
    files = [x for x in txt_folder]

    for file_name in files:
        with open(file_name, 'r') as f:
            new_content = []
            current_iteration = n_iteration
            lines = f.readlines()
            for text_line in lines:
                if regex.match(text_line):
                    new_content.extend(new_volume_lines(current_iteration))
                    current_iteration += 1
                else:
                    new_content.append(text_line)
            f.close()

        with open(file_name, 'w') as f:
            for new_line in new_content:
                f.write(new_line)
            f.close()


def new_volume_lines(current_iteration):
    return [
        '3 {0} \"volume_{0}\"\n'.format(i + 1) for i in range(current_iteration)
    ]

Run example, let's say we have a txt at "./path/to/folder"

$MeshFormat
2.2 0 8
3 1 "volume_1"
$EndPhysicalNames

If we run:

process_files('./path/to/folder', 3)

the file will end up like this:

$MeshFormat
2.2 0 8
3 1 "volume_1"
3 2 "volume_2"
3 3 "volume_3"
$EndPhysicalNames
Sign up to request clarification or add additional context in comments.

3 Comments

Dear @Manu, I do appreciate you for giving time to my problem. I have a question. What should I write in front of the last for? It should be the last for condition in my first code?
ok, I'm updating the answer to a complete-working solution
Thank you, I appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.