This is a improved version of the program seen in my older question.
This program first displays a menu which shows some options that the user can select. Each option will the respective functions which do some things.
The user can insert a filename, read data from it, enter a regex pattern, test if each line of the file matches the given regex pattern.
Please provide feedback on how I can improve my program.
import re
def test_data(readData, regex):
'''Checks if each line of data matches the regex'''
if not regex:
print('Empty regex')
print('')
return
try:
pattern = re.compile(regex)
except:
print('Invalid regex')
print('')
return
if not readData:
print('Read data is empty')
print('')
return
for i, line in enumerate(readData, 1):
line = line.strip() #Strip off the newline character from each line
if pattern.match(line):
print(' Line ', i, ':"', line,'"', ' matches current regex', sep='')
else:
print(' Line ', i, ':"', line,'"', ' does not match current regex', sep='')
print('')
def change_regex(regex):
'''Sets the regex variable'''
regex = '"%s"' % regex if regex else 'empty'
print('Current regex is', regex)
regex = input('Enter new regex: ')
print('')
return regex
def read_file(filename):
'''Reads data from file if possible'''
try:
with open(filename, "r") as file:
readData = file.readlines()
print('Data read successfully!')
return readData
except TypeError:
print('filename is empty!')
except FileNotFoundError:
print('File not found!')
print('')
def change_filename(filename):
'''Sets the filename variable'''
filename = '"%s"' % filename if filename else 'empty'
print('Current filename is', filename)
filename = input('Enter new filename (with extension): ')
print('')
return filename
def main():
filename = regex = readData = None
while True:
print('Enter 1 to change filename')
print('Enter 2 to read file')
print('Enter 3 to change regex')
print('Enter 4 to test if read data matches given regex')
print('Enter 5 to exit')
try:
option = int(input('Option: '))
except:
print('Invalid input')
print('Please enter a valid option')
print('')
continue
if option == 1:
filename = change_filename(filename)
elif option == 2:
readData = read_file(filename)
elif option == 3:
regex = change_regex(regex)
elif option == 4:
test_data(readData, regex)
elif option == 5:
break
else:
print('Invalid input')
print('Please enter a valid option')
print('')
if __name__ == "__main__":
main()