Read and Append the specific content

懵懂的女人 提交于 2019-12-24 11:27:17

问题


Subsequent to my previous question what if I want to append line. In that case others block are also specified in 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

Outputfile file2.txt

##### Xyz


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

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

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

The output file is predefined structure as shown in output file - file2.txt with specified blocks. If some new items content * [x] are added in input file it shall append in output file, shall not add any duplicate items. It would be interesting to see the usage of argparse and append one specific block or entire block start with [x]. Thanks :)


回答1:


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

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)


来源:https://stackoverflow.com/questions/30967710/read-and-append-the-specific-content

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!