2017-10-18 36 views
0

因此,我有幾個.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名單我已經有結構在這種情況下TRSVDY

所以在for line in f循環我想借此文/中Structures: structures[i]線和Structures: structures[i+1]並將其保存到一個文本文件之間的數據,然後再去做,直到structures名單已通過環。但如前所述,當我到達最後一部分時,沒有結束Structures: structures[i+1],因此我得到一個錯誤。這個錯誤是我想要避免的。

+0

你可以請包括一些樣本輸入和輸出?我讀了幾次,我不確定我明白你想要做什麼。 – roganjosh

+0

在2秒內出現... –

回答

1

一個簡單的解決方案是簡單地將一個虛擬structure添加到structures的末尾,該末尾不會出現在文件中的任何位置。 然後你可以寫你的循環是這樣的:

for structure1, structure2 in zip(structures[:-1], structures[1:]): 

這將遍歷所有成對的連續結構。

另一種解決方案(避免使用虛設結構的)。將取代

elif line.strip() == "Structure: {}".format(structures[i+1]): 

elif i+1 != len(structures) and line.strip() == "Structure: {}".format(structures[i+1]): 

條件(這將導致誤差)的第二部分將不評估第一部分是否爲假。如果你決定使用這個版本中,你可能會想,你實際上並沒有使用可變structure任何地方

for i in range(len(structures)): 

更換

for i, structure in enumerate(structures): 

+0

這樣可以消除錯誤是的,但它不會「取走」最後一個結構和最後沒有第二個結構的文本/數據...... –

+1

@DenverDang對不起錯過了。看到更新,我希望這一次,它是你想要的:) – Knoep

+0

虛擬的東西是優秀的,也許是最簡單的方法來做到這一點,即時通訊:)它現在的作品。謝謝 ! –

相關問題