2017-02-25 50 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够公平:)有一个很好的 –

相关问题