我正在嘗試讀取file1.txt的特定內容,並將此特定內容寫入另一個文件file2.txt中。問題是我讀完Bar後的所有部分,我只想讀取[x]開頭的行,並且只讀取Bar部分。讀取並寫入特定內容
源代碼
def read_write_file_content():
data_file = open('file1.txt')
block = ""
found = False
for line in data_file:
if found:
if line.strip() == "##### Foo":
break
else:
block += line
else:
if line.strip() == "##### Bar:":
found = True
block = line
print block
data_file.close()
view_today()
輸入文件 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
##### Bar:
* [x] Email to A
* [x] Email to C
任何建議將不勝感激?謝謝:)
請[edit]添加一個特定的問題陳述 - 「不起作用」可以假設,但* how *不起作用?什麼錯誤信息或不正確的行爲是特徵? –
if'[x]'in line:? –
是的。 [x]在行首。有些行是[],這不是我們的考慮因素。 – Roujri