![](/img/trans.png)
[英]How do I use python 3 to find a certain text line and copy the lines below it?
[英]I need to find a line of text in python and copy it, and the lines above and below it
基本上,我需要在python(和tk)中找到一行文本並將其復制,以及其上方和下方的行。
Imported_File = a long list of strings.
One_Ring = the line I'm looking for.
在Imported_File中找到One_ring,復制One_ring,將其上方和下方的行復制到Output_Var
我真的很困,任何幫助都將是驚人的。
我認為您正在尋找確切的路線
imported_file = ['a', 'b', 'c', 'd', 'e', 'f']
one_ring = 'd'
if one_ring in imported_file:
i = imported_file.index(one_ring)
start = i-1
end = i+2
# problem with first element before "a" when `one_ring = 'a'`
if start < 0:
start = 0
output_var = imported_file[start:end]
print(output_var)
else:
print('not found')
BTW:使用lower_case
為varaibles名稱: PEP 8 -風格指南Python代碼
考慮到您正在從具有這些長字符串列表的文件中讀取。
with open('textFile.txt') as f:
Imported_File = f.readlines()
One_Ring = "This is the line\n"
Output_Var = ""
if One_Ring in Imported_File:
idx = Imported_File.index(One_Ring)
Output_Var = Imported_File[max(0, idx - 1):idx+2]
print(Output_Var)
textFile.txt將是您的輸入文件。 我創建了一個示例文件,看起來像
Hello there
How are you
This is the line
Done, Bye
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.