问题
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