-1

I wrote a little program that allows the user (using inquirer) to either edit or add a new line to a file

import inquirer


def edit_line(file):
   a_file = open(file, 'r')
   print('Your file: \n' + open(file).read())
   list_of_lines = a_file.readlines()
   index = int(input('What line would you like to edit?: ')) - 1
   list_of_lines[index] = input('Write your text here: ') + '\n'

   a_file = open(file, 'w')
   a_file.writelines(list_of_lines)
   a_file.close()
   print(('\nYour new file:\n' + open(file).read()))


def add_line(file):
   a_file = open(file, 'a')
   print('Your file: \n' + open(file).read())
   a_file.write('\n' + input('Enter text to add: '))
   a_file.close()
   print(('Your new file:\n' + open(file).read()))


def op_cselector():
   questions = [
       inquirer.List('operation',
                     message='What would you like to do?: ',
                     choices=['Add line', 'Edit line']
                     )
   ]
   answers = inquirer.prompt(questions)
   return answers['operation']


if op_cselector() is 'Add line':
   add_line('sample.txt')
elif op_cselector() is 'Edit line':
   edit_line('sample.txt')

It works fine when I choose the first option, but when i choose the second one it asks the question again. This time if I choose the second option the program works as intended, but if i change my decision it terminates without errors.

How do I fix this? Maybe there is a different module I should use?

I like inquirer, because it looks great and works great in a terminal, but I'm not that great at using it :/

1 Answers1

1
if op_cselector() is 'Add line':
   add_line('sample.txt')
elif op_cselector() is 'Edit line':
   edit_line('sample.txt')

You are calling op_cselector twice so the input is shown twice... You should call it once and save the result in a variable. Also, strings should be compared with ==, not is.

op = op_cselector()
if op == 'Add line':
   add_line('sample.txt')
elif op == 'Edit line':
   edit_line('sample.txt')
DeepSpace
  • 78,697
  • 11
  • 109
  • 154