Simple line input with reentering possibility, unlimited lines

TrustyTony 4 Tallied Votes 510 Views Share

Here some old fashioned line input routine, better idea nowadays would be to use GUI input box with real editing.

Anyway, it is quite simple with Python to do this basic routine for terminal based program.

""" Allow reinput of lines of data
    Single 'e' or 'q' as line is not allowed, except 'q' in edit mode is OK

    For daniweb.com by Tony Veijalainen, user pyTony
"""

# Make to work in Python 2 and Python 3
from __future__ import print_function
try:
    input = raw_input
except:
    pass

data = []
line = ''
while True:
    line = input('Enter a datum {}: '.format(len(data)+1))
    if line == 'q':
        break
    elif line == 'e':
        print('Edit mode, "e" exits edit mode, empty line leaves unchanged.')
        for lineno, line in enumerate(data, 1):
            print(lineno, ':', line)
            line = input('e> ')
            if line == 'e':
                break
            else:
                if not line:
                    print('Not changing')
                else:
                    data[lineno-1] = line
        print('Exiting edit mode, now lines are:')
        print(*data, sep='\n')
    else:
        data.append(line)
    
    
print('You input {} data lines:'.format(len(data)))
print(*data, sep='\n')

""" Example session:
Enter a datum 1: 42
Enter a datum 2: 43
Enter a datum 3: d
Enter a datum 4: e
Edit mode, "e" exits edit mode, empty line leaves unchanged.
1 : 42
e> 
Not changing
2 : 43
e> 
Not changing
3 : d
e> 76
Exiting edit mode, now lines are:
42
43
76
Enter a datum 4: 65
Enter a datum 5: y
Enter a datum 6: 43
Enter a datum 7: 23
Enter a datum 8: e
Edit mode, "e" exits edit mode, empty line leaves unchanged.
1 : 42
e> 
Not changing
2 : 43
e> 
Not changing
3 : 76
e> 
Not changing
4 : 65
e> 
Not changing
5 : y
e> 98
6 : 43
e> e
Exiting edit mode, now lines are:
42
43
76
65
98
43
23
Enter a datum 8: 221
Enter a datum 9: q
You input 8 data lines:
42
43
76
65
98
43
23
221
"""
fonzali 0 Light Poster

thanks pytony for the code , I have written a program for my own business but it lacked a code like yours . with your permission I will use it .

TrustyTony 888 pyMod Team Colleague Featured Poster

This is of course public domain as long as you do not claim having witten it yourself. You might also be interested in some my elder GUI snippets, like http://www.daniweb.com/software-development/python/code/283859/tkinter-info-grid-by-loops-and-tuples

fonzali 0 Light Poster

thanks again pytony , I can use the above code too and do not worry , I will not claim it as my own

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.