2017-02-25 90 views
0
def improve_fight_song(title): 
    Tech_file = open("RamblinWreck.txt","r") 
    myfile= open("ImprovedFightSong.txt","w") 
    lines = Tech_file.readlines() 

#Lets find all of the engineer cases. 
    for s in range(len(lines)): 
     if "engineer" in lines[s]: 
      z = lines[s].replace("engineer","programmer") 
      myfile.write(z) 



    myfile.close() 

improve_fight_song("kjhk") 

我似乎無法弄清楚爲什麼我在這裏超出範圍。我試圖通過線的長度來獲取for循環,這只是所有行的列表,但這也行不通。下面是實際的錯誤信息爲什麼我得到索引超出範圍錯誤?

回溯(最近通話最後一個): 文件 「/Users/treawethington/Documents/HW6.py」,第16行,在 improve_fight_song( 「kjhk」) 文件「/用戶/ treawethington /文檔/ HW6.py」,8號線,在improve_fight_song 如果‘工程師’的行[S]: IndexError:列表索引超出範圍

+1

是否有隻有10 Tech_file線? –

+1

同樣,你爲什麼選擇'range(11)'來控制你的循環? – Chris

+0

不,有12個。但是我已經嘗試了11,12,13,對於範圍,我仍然得到相同的錯誤。 – Trea704

回答

0

你更新的代碼運行正常,當我測試了它,但我認爲你在找什麼:

def improve_fight_song(): 
    tech_file = open("RamblinWreck.txt", "r") 
    myfile = open("ImprovedFightSong.txt", "w") 
    lines = tech_file.readlines() 

    # Lets find all of the engineer cases. 
    for line in lines: # no need for range here 
     if "an engineer" in line: 
      myfile.write(line.replace("an engineer", "a programmer")) 
     else: 
      myfile.write(line) 

    myfile.close() 
    tech_file.close() # close this file as well 


improve_fight_song() 

其中thisRamblinWreck.txt的內容,this是運行HW6.py後的內容ImprovedFightSong.txt

0

您通常不應該按索引遍歷行列表。只需使用:

for s in lines: 
    if 'engineer' in s: 
     z = s.replace('engineer', 'programmer') 

請注意,您的原始代碼寫道,已經改變了線路。

相反遍歷所有行的,你可能只是做替換該文件的全部內容:

with open("RamblinWreck.txt","r") as infile: 
    text = infile.read() 

outtext = text.replace('engineer', 'programmer') 

with open("ImprovedFightSong.txt","w") as outfile: 
    outfile.write(outtext) 
+0

這是爲了避免內存問題,你沒有在打開時使用嵌套'with'語句?('b.txt','w')作爲b: b.write(a.read()。replace('engineer')打開('a.txt','r') ,'programmer'))' –

+0

@MaxChrétien簡單勝於複雜。 ;-) –

+0

ahah夠公平:)有一個很好的 –

相關問題