我想將文本檔案的特定部分(使用特殊字串,例如 #)移動到另一個檔案。喜歡:類似的解決方案。我的問題是我還想在輸出檔案中指定目標。
例如
我有一個文本檔案,其中一段以 #1 開頭,在某些行之后以 #2 結尾
FIle1.txt
hello
a
b
#1
a
b
#2
c
我有另一個檔案(不是txt而是markdown),如下所示:
File2
header
a
b
#1
#2
d
我想將特殊字符(#1 和 #2)內的文本從第一個檔案移動到第二個檔案中。結果是:
File2
header
a
b
#1
a
b
#2
d
uj5u.com熱心網友回復:
IIUC,你想要:
with open("file1.txt") as f:
f1 = [line.strip() for line in f]
with open("file2.md") as f:
f2 = [line.strip() for line in f]
output = f2[:f2.index("#1")] f1[f1.index("#1"):f1.index("#2")] f2[f2.index("#2"):]
with open("output.md", "w") as f:
f.write("\n".join(output))
uj5u.com熱心網友回復:
我寫了一個不太 Pythonic 的例子,如果你有更多的錨點,它更容易修改。它使用一個非常簡單的狀態機。
to_copy = ""
copy_state = False
with open("file1.txt") as f:
for el in f:
# update state. We need to leave copy state before finding end symbol
if copy_state and "#2" in el:
copy_state = False
if copy_state:
to_copy = el
# update state. We need to enter copy state after finding end symbol
if not copy_state and "#1" in el:
copy_state = True
#debug
print(to_copy)
output = ""
with open("file2.txt") as fc:
with open("file_merge.txt","w") as fm:
for el in fc:
#copy file 2 into file_merge
output = el
#pretty much the same logic
# update state. We need to leave copy state before finding end symbol
if copy_state and "#2" in el:
copy_state = False
# update state. We need to enter copy state after finding end symbol
if not copy_state and "#1" in el:
copy_state = True
# if detected start copy, attach what you want to copy from file1
output = to_copy
fm.write(output)
#debug
print(output)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/342536.html
