为什么我的索引超出范围错误?

时间:2017-02-25 15:10:33

标签: python csv

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行,in     improve_fight_song( “kjhk”)   在improve_fight_song中输入文件“/Users/treawethington/Documents/HW6.py”,第8行     如果行[s]中的“工程师”: IndexError:列表索引超出范围

2 个答案:

答案 0 :(得分: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()

运行RamblinWreck.txtImprovedFightSong.txt的内容为HW6.pythis的内容为{{1}}的内容。

答案 1 :(得分: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)