繁体   English   中英

在代码完成编辑文本文件后,我不断收到错误,IndexError: list assignment index out of range

[英]I keep getting an error, IndexError: list assignment index out of range, after the code finishes editing the text file

我试图将行号放在文件中的文本旁边,但完成后它显示错误。 为什么? 另外,不确定它是否显示,但在 import.txt 中,出于某种原因,在最后一个文本之后必须有一个空行。

错误:

Traceback (most recent call last):
  File "main.py", line 21, in <module>
    replace_line("import.txt",(count),(whole))
  File "main.py", line 10, in replace_line
    lines[line_num] = text
IndexError: list assignment index out of range

代码:

import time, sys, random, os
count = -1
read = open("import.txt","r")
while input("Press Enter to continue...") != "End":
  open("import.txt",'r').close()
  os.system('clear')
  ask = input("Type run: ")
  def replace_line(file_name, line_num, text):
      lines = open(file_name, 'r').readlines()
      lines[line_num] = text
      edt = open(file_name,'w')
      edt.writelines(lines)
      edt.close()
  if ask == "run" or ask == "Run":
    for line in read:
      count += 1
      prefix = ("["+str((count)+1)+"] ")
      if (prefix) not in line:
        time.sleep(0.2)
        whole = (str(prefix)+str(line))
        replace_line("import.txt",(count),(whole))
      else:
        continue
    open("import.txt",'r').close()

之前导入.txt

Test 1
Test 2
Test 3

导入.txt

[1] Test 1
[2] Test 2
[3] Test 3

让代码工作的最简单方法是将lines[line_num] = text更改为lines[line_num - 1] = text并从0开始count 这样做的原因是, count不断增加,并且始终比您真正要替换的索引领先 1。

切线......我强烈建议只打开这个文件一次,处理每一行,然后写一次。 目前,您在代码中至少打开文件 5 次。 这不仅效率低下,而且会使调试更加困难。 事实上,您在这里甚至不需要用户交互,对吗? 我会考虑进一步模块化。 您真正需要的是 readlines() 函数、自定义修改函数和 writelines() 函数。

这是我在想的一种实现:

file_name = 'import.txt'
with open(file_name, 'r') as f:
    data = f.readlines()

new_lines = []
for count, line in enumerate(data):
    new_line = '[{}] {}'.format(count + 1, line)
    new_lines.append(new_line)

with open(file_name, 'w') as f:
    data = f.writelines(new_lines)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM