【问题标题】:Why am I getting an index out of range error?为什么会出现索引超出范围错误?
【发布时间】:2017-02-25 15:10:33
【问题描述】:
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 循环有趣,这只是所有行作为字符串的列表,但这也不起作用。以下是实际的错误信息

Traceback(最近一次调用最后一次): 文件“/Users/treawethington/Documents/HW6.py”,第 16 行,在 改善战斗歌曲(“kjhk”) 文件“/Users/treawethington/Documents/HW6.py”,第 8 行,在改进_fight_song 如果行[s]中的“工程师”: IndexError: 列表索引超出范围

【问题讨论】:

  • Tech_file只有10行吗?
  • 同样,你为什么选择range(11)来控制你的循环?
  • 不,有 12 个。但是我已经尝试了 11、12、13 的范围,但我仍然得到同样的错误。
  • 您应该输出循环的每次迭代中发生的事情,以查看正在发生的事情,您肯定会弄明白的。此外,您不需要像那样循环您的线路。您可以只执行 for line in lines 并且每个 line 将成为您列表中的行,因此您可以简单地检查迭代中获得的每一行的相等性。
  • 您能发布完整的异常回溯吗?这段代码应该不可能抛出 IndexError。

标签: python csv


【解决方案1】:

我测试时你更新的代码运行良好,但我认为你正在寻找的是:

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.pyImprovedFightSong.txt 的内容。

【讨论】:

    【解决方案2】:

    您通常不应该按索引循环遍历行列表。只需使用:

    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)
    

    【讨论】:

    • 是为了避免内存问题,您在打开时没有使用嵌套的with 语句吗? with open('a.txt', 'r') as a, open('b.txt', 'w') as b: b.write(a.read().replace('engineer', 'programmer'))
    • @MaxChrétien 简单胜于复杂。 ;-)
    猜你喜欢
    • 2016-08-22
    • 2017-12-02
    • 1970-01-01
    • 2020-09-04
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    相关资源
    最近更新 更多