Python编辑行

Python编辑行,python,python-2.7,Python,Python 2.7,我正在创建一个小程序来编辑文本文件中的文本行 我不断地犯错误 我的代码: 我的错误: 我建议您尝试一下,但您的代码如下所示: 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 te

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

我不断地犯错误

我的代码:

我的错误:


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

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
当然,您可以通过检查文件是否成功打开来进一步改进这一点


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

@KenWhite Dw,在您的注释后添加了标记:-@热带河马请上传你正在使用的文件。感谢编辑我仍然是新的,正在学习如何在这里正确地贡献和提问。嘿,伙计,欢迎你,非常感谢你的帮助,我仍然是非常新的,正在学习,很难知道从何处获得好的帮助。
    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
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