Search code examples
pythonos.path

How to make sure that information from one file is duplicated into several text documents, without specific lines


We need a code in pyhon that will create several text documents in which only information about the letter v will be written, and after the letter f create a text document with the next letter v, the information is taken from the text document text.txt

text.txt:
v 123 123 123
v 123 123 123
v 123 123 123
vt 123 123 123
vn 123 123 123
f 12345 12345 12345
v 231 321 321
v 231 321 321
v 231 321 321
v 231 321 321
vt 321 312 321
vn 312 312 321
f 54321 54321 54321

I was only able to write code that will create a new text document, only with the letter v, but I don’t understand how to make sure that each time a new text document is created for the letter v after the letter f, but at the same time that the new text document also contains information about letter v

if is_obj:
    w = open("mid.txt", "w")
    r = open(f"object.obj", "r")
    def treat():
        if line[0] == 'v':
            if line[1] == ' ':
                w.write(line)
    with open(f'object.obj') as read:
        for i in read:
            for line in read:
                treat()

Solution

  • If you want to create files dynamically, you will need to generate a file name. One of the approaches is to add the next number to the name.

    def num_gen(num):
        """Generate next number for the file name."""
    
        while True:
            yield num
            num += 1
    
    
    counter = num_gen(1)  # Generator of numbers for each text file name.
    

    Open the source file and read all the lines:

    with open('text.txt') as sf:
        lines = sf.readlines()
    

    Loop through the lines, append to the list all the lines that start from 'v', and write a new file, when it comes to 'f'.

    v_list = list()
    
    for line in lines:
        if line.startswith('v '):
            v_list.append(line)
    
        elif line.startswith('f '):
            if v_list:
                with open(f'text_{next(counter)}.txt', 'w') as file:
                    for v_line in v_list:
                        file.write(v_line)
                v_list.clear()