Python编辑行

时间:2018-01-06 22:39:32

标签: python python-2.7

我正在创建一个程序来编辑文本文件中的文本行。

我不断收到错误。

我的代码:

def Main():

    myfile = raw_input("Please enter the name of the file you wish to edit: ")
    change = input("please enter the line number you wish to change: ")
    newLine = raw_input("please enter the new text: ")

    f = open(myfile, 'r')
    content = f.readlines()
    f.close()

    f = open(myfile, 'w')
    content[change-1] = newLine + '\n'
    f.writelines(content)

    #the for loop is just for checking it worked!!
    for things in content:
        print things

    f.close()

我的错误:

    Traceback (most recent call last):

    File "/home/hippopotamus/Desktop/Server and Client Project/Client/Edit.py", line 21, in <module>

    Main()

    File "/home/hippopotamus/Desktop/Server and Client Project/Client/Edit.py", line 11, in Main

    content[change-1] = newLine + '\n'
    IndexError: list assignment index out of range

1 个答案:

答案 0 :(得分:2)

我建议您尝试一下,以便您的代码如下所示:

myfile = raw_input("Please enter the name of the file you wish to edit: ")
change = input("please enter the line number you wish to change: ")
newLine = raw_input("please enter the new text: ")

f = open(myfile, 'r')
content = f.readlines()
f.close()

try:
  content[change-1] = newLine + '\n'
  f = open(myfile, 'w')
  f.writelines(content)
  f.close()
except IndexError:
  print "Specified line number out of range"

#the for loop is just for checking it worked!!
for things in content:
    print things

当然,您可以通过检查文件是否成功打开来进一步改进。

如果这不能解决(或至少表明)您的问题,请确保您使用的文件具有正确的换行符,并且它们是预期的位置。