Reading and adding specific content

Following my previous question, what if I want to add a line. In this case, other blocks are also specified in the output file.

Input file file1.txt

##### Xyz
* [] Task 112
* [] Cl 221

##### Foo
* [] Task 1
* [x] Clone 2

##### Bar:
* [x] Email to A
* [] Email to B
* [x] Email to C

##### Bob
* [] Task 3
* [x] Clone Bob

      

Output file file2.txt

##### Xyz


##### Foo
* [x] Clone 2

##### Bar:
* [x] Email to A
* [x] Email to C

##### Bob
* [x] Clone Bob

      

The output file is a predefined structure as shown in the output file - file2.txt with the specified blocks. If the content of new elements * [x] is added in the input file, it must be added to the output file, it must not add duplicates. It would be interesting to see the use of argparse and add one specific block or an entire block using [x]. Thank:)

+1


source to share


1 answer


Read all lines from the input file, but write only those that start with the specified lines:



with open("file1.txt", "rt") as finp:
    with open("file2.txt", "wt") as fout:
        for line in finp.readlines():
            if line.startswith("#####") or line.startswith("* [x]"):
                fout.write(line)

      

+1


source







All Articles