2017-02-09 74 views
1

我想用代碼自動編輯.txt文件。包含victory_poins的所有內容都將被刪除,並在「history = {」語句後以另一種形式輸入。但最後,它增加了一個額外的歷史= {。爲什麼?編輯.txt文件 - 算法不工作

代碼:

def überschreiben(filename,vp, capital): 
data_out=open(filename,"r") 
data_in=open(filename+"_output.txt","w") 

vpsegment=False 
for line in data_out: 
    if "\thistory" in line: 
     data_in.write(line+'\n\t\tvictory_points = { '+str(capital)+' '+str(vp)+' }\n') 

    if "\t\tvictory_points" in line: 
     vppivot=line 
     vpsegment=True 

    if vpsegment==True: 
     if "}" in line: 
      data_in.write("") 
      vpsegment=False 
     else: 
      data_in.write("") 
    else: 
     data_in.write(line) 
data_in.close() 
data_out.close() 

輸入:

state={ 
id=1 
name="STATE_1" # Corsica 
manpower = 322900 

state_category = town 

history={ 
    owner = FRA 
    victory_points = { 3838 1 } 
    buildings = { 
     infrastructure = 4 
     industrial_complex = 1 
     air_base = 1 
     3838 = { 
      naval_base = 3 
     } 
    } 
    add_core_of = FRA 
} 

provinces={ 
    3838 9851 11804 
} 
} 

輸出:

[...] 

state_category = town 

history={ 

    victory_points = { 00001 8 } 
history={ 
    owner = FRA 
    buildings = { 
     infrastructure = 4 
     industrial_complex = 1 
     air_base = 1 
     3838 = { 
      naval_base = 3 
     } 
    } 
    add_core_of = FRA 
} 

provinces={ 
    3838 9851 11804 
} 
} 

哪裏第二歷史= {從何而來?

+0

它只輸出一個'history = {'line for me。 – yper

+0

'「\ thistory」'是在行中,所以它寫了第一個歷史。然後'vpsegment == False',所以你去else語句並且寫下這行(它包含「'history {'」) – Fabich

回答

1

讓我們來看看,當你閱讀的行history{會發生什麼:

if "\thistory" in line: 
    data_in.write(line+'\n\t\tvictory_points = { '+str(capital)+' '+str(vp)+' }\n') 

該行包含「\ thistory」,所以它寫入線(寫入第一個「歷史{」)和其他的東西

if "\t\tvictory_points" in line: 
    vppivot=line 
    vpsegment=True 

什麼也沒有發生,因爲該行不包含 「\ t \ tvictory_points」

if vpsegment==True: 
    if "}" in line: 
     data_in.write("") 
     vpsegment=False 
    else: 
     data_in.write("") 
else: 
    data_in.write(line) 

vpsegment==False所以它進入else語句並且寫入的行是"\thistory{"