[英]copy section of text in file python
我需要從下面的文本文件中提取值:
fdsjhgjhg
fdshkjhk
Start
Good Morning
Hello World
End
dashjkhjk
dsfjkhk
我需要提取的值是從開始到結束。
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
copy = False
for line in infile:
if line.strip() == "Start":
copy = True
elif line.strip() == "End":
copy = False
elif copy:
outfile.write(line)
我正在使用的上面的代碼來自這個問題: 使用python提取文本文件中兩個字符串之間的值
該代碼將不包含字符串“ Start”和“ End”,僅包含它們內部的內容。 您將如何包括周邊字符串?
@en_Knight幾乎正確。 這是一個滿足OP要求在輸出中包含定界符的修復程序:
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
copy = False
for line in infile:
if line.strip() == "Start":
copy = True
if copy:
outfile.write(line)
# move this AFTER the "if copy"
if line.strip() == "End":
copy = False
或僅在適用於以下情況的情況下包括write():
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
copy = False
for line in infile:
if line.strip() == "Start":
outfile.write(line) # add this
copy = True
elif line.strip() == "End":
outfile.write(line) # add this
copy = False
elif copy:
outfile.write(line)
更新 :要回答注釋“僅在'開始'之后使用'結束'的第一次出現”中的問題,請將最后一個elif line.strip() == "End"
更改為:
elif line.strip() == "End" and copy:
outfile.write(line) # add this
copy = False
如果只有一個“開始”行但有多個“結束”行,則此方法有效……聽起來很奇怪,但這是發問者所要求的。
“ elif
”的意思是 “僅在其他情況失敗時才執行此操作”。 如果您來自類似C語言的不同語言, 則在語法上等效於“ else if
”。 沒有它,失敗應該注意包括“開始”和“結束”
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
copy = False
for line in infile:
if line.strip() == "Start":
copy = True
if copy: # flipped to include end, as Dan H pointed out
outfile.write(line)
if line.strip() == "End":
copy = False
RegExp方法:
import re
with open('input.txt') as f:
data = f.read()
match = re.search(r'\n(Start\n.*?\nEnd)\n', data, re.M | re.S)
if match:
with open('output.txt', 'w') as f:
f.write(match.group(1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.