0

So I've written a simple program that allows user to enter a line they would like to edit and text they would like to put into that line

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')

When I run the program it works fine. However, It asks the user to input the text first and the line number second.

What is the reason for this and how can I fix it?

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 1
    Don't squeeze so much in one line. Prompt the stuff you want first in a separate statement. – ThiefMaster Jun 26 '22 at 10:44
  • You can fix it by separating it to two lines [Is python assignment strictly evaluated right to left?](https://stackoverflow.com/questions/29753335/is-python-assignment-strictly-evaluated-right-to-left) – Guy Jun 26 '22 at 10:45
  • Calling *input()* in code structures like that is bad practice. Of course it can work if you understand the order of evaluation. Separate (and validate) the inputs and you'll find life much easier – DarkKnight Jun 26 '22 at 12:43

2 Answers2

1

If you want to fix the problem, just split the one line into two:

Instead of:

list_of_lines[int(input('What line would you like to edit?: ')) - 1] = input('Write your text here: ') + '\n'

Do:

 index = int(input('What line would you like to edit?: ')) - 1
 list_of_lines[index] = input('Write your text here: ') + '\n'

And as the answer @Guy linked explains, when you are doing an assignment line of code, the right hand (value of the variable) is run before the left side.

Aniketh Malyala
  • 2,650
  • 1
  • 5
  • 14
0

Validation is everything! What would happen if the user's input for the line number wasn't within the range of lines read from the file?

Here's a more robust approach:

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')
DarkKnight
  • 19,739
  • 3
  • 6
  • 22