[英]Why am I getting an index out of range error?
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行,在perform_fight_song(“ kjhk”)中,文件“ /Users/treawethington/Documents/HW6.py”,第8行,在如果第幾行中的“工程師”,則為perfect_fight_song:IndexError:列表索引超出范圍
當我測試您更新的代碼時,它運行良好,但是我認為您正在尋找的是:
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()
通常,您不應該按索引遍歷行列表。 只需使用:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.