因此,我有幾個.txt文件,每個文件中有超過500.000行。 在他們所有的我有我想要提取到他們自己的.txt文件的部分。在文本文件中的某些字符串之間寫入數據(最後一個元素錯誤)
對於這個我用下面的代碼:
for i, structure in enumerate(structures):
with open("data.txt", 'r') as f:
structure_data = open('data_new.txt'), 'w')
copy = False
for line in f:
if line.strip() == "Structure: {}".format(structures[i]):
structure_data.write(line)
copy = True
elif line.strip() == "Structure: {}".format(structures[i+1]):
copy = False
elif copy:
structure_data.write(line)
structure_data.close()
f.close()
這裏structures
是的,是的名單,結構我有。
因此,基本上在每個.txt文件中都有一行說Structure: <some structure in the structures list>
。我現在希望提取數據文件中兩個字符串structures[i]
和structures[i+1]
之間的數據。在我上面的例子它這樣做,並且我得到我想要的數據新的.txt文件,但是,我得到的.txt文件,我得到了以下錯誤:
elif line.strip() == "Structure: {}".format(structures[i+1]):
IndexError: list index out of range
這樣做的原因,據我所知,對於.txt文件的最後部分,沒有「結束」Structure: <structure>
,所以它不能設置copy = False
。
因此,我確實得到了我想要的.txt文件輸出,但正如您所知,沒有什麼更糟糕的代碼有錯誤。那麼有沒有辦法告訴它,如果沒有這樣的「終點線」,那麼eveything是好的?
UPDATE: 這是在data.txt
的數據可能有點像:
Structure: TR
Dose [cGy] Ratio of Total Structure Volume [%]
0 100
0.100619 100
0.2
0.301857 100
0.402476 100
0.503096 100
0.603715 100
0.704334 100
0.804953 100
0.905572 100
Structure: SV
Dose [cGy] Ratio of Total Structure Volume [%]
0 100
0.100619 100
0.2
0.301857 100
0.402476 100
0.503096 100
0.603715 100
0.704334 100
0.804953 100
0.905572 100
Structure: DY
Dose [cGy] Ratio of Total Structure Volume [%]
0 100
0.100619 88.2441
0.2.4882
0.301857 64.7324
0.402476 52.9765
0.503096 41.2206
0.603715 29.4647
0.704334 17.707
0.804953 17.6784
0.905572 17.6499
所以在structures
名單我已經有結構在這種情況下TR
,SV
和DY
。
所以在for line in f
循環我想借此文/中Structures: structures[i]
線和Structures: structures[i+1]
並將其保存到一個文本文件之間的數據,然後再去做,直到structures
名單已通過環。但如前所述,當我到達最後一部分時,沒有結束Structures: structures[i+1]
,因此我得到一個錯誤。這個錯誤是我想要避免的。
你可以請包括一些樣本輸入和輸出?我讀了幾次,我不確定我明白你想要做什麼。 – roganjosh
在2秒內出現... –