所以我写了一个简单的程序允许用户输入他们想要编辑的行和他们想要在那行中输入的文本
def edit_line(file):
a_file = open(file, 'r')
list_of_lines = a_file.readlines()
list_of_lines[int(input('What line would you like to edit?: ')) - 1] = input('Write your text here: ') + 'n'
a_file = open(file, 'w')
a_file.writelines(list_of_lines)
a_file.close()
edit_line('sample.txt')
当我运行程序时,它工作得很好。但是,它要求用户先输入文本,然后输入行号。
这是什么原因,我怎么能解决它?
如果您想解决这个问题,只需将一行分成两行:
代替:
list_of_lines[int(input('What line would you like to edit?: ')) - 1] = input('Write your text here: ') + 'n'
:
index = int(input('What line would you like to edit?: ')) - 1
list_of_lines[index] = input('Write your text here: ') + 'n'
正如答案@Guy链接解释的那样,当你在执行赋值行代码时,右边(变量的值)在左边之前运行。
验证就是一切!如果用户输入的行号不在从文件中读取的行范围内,会发生什么情况?
这里有一个更健壮的方法:
def edit_line(filename):
with open(filename, 'r+') as file:
lines = file.readlines()
while True:
try:
lineno = int(input('What line would you like to edit: '))
if 0 <= lineno < len(lines):
lines[lineno] = input('Write your text here: ') + 'n'
file.seek(0)
file.writelines(lines)
file.truncate()
break
else:
raise ValueError('Line number out of range')
except ValueError as e:
print(e)
edit_line('edit.txt')