In: Computer Science
I would like the following code in PYTHON please, there was a previous submission of this question but I am trying to have the file save as a text file and not a json. Any help would be greatly appreciated.
Create an application that does the following:
The user will enter product codes and product numbers from the
keyboard as strings. The product code must consist of four capital
letters. The product number can only consist of numeric characters,
but the first character must be a zero. If data is entered that
doesn't fit the above characteristics, prompt the user to try
again.
Once the user enters data in the correct format, add the data to a
Dictionary object. The product code should be the key and the
product number should be the value.
The above occurs in a loop, so the user can enter multiple
code/number values into the Dictionary object. Make sure your loop
has a procedure to end at the user's request.
Once the user has finished putting data into the Dictionary object,
serialize the Dictionary object to file. The user should be able to
provide a file name for the serialized Dictionary object.
Example of the output of a run of the program:
Enter a product code (four capital letters): ABCD
Enter a product number (a number with a leading 0):
012345
Do you wish to continue? Enter y/n: y
Enter a product code (four capital letters): aDDE
That was not a correct product code, please try again:
ADDE
Enter a product number (a number with a leading 0):
01234A
That was not a correct product number, please try again:
012340
Do you wish to continue? Enter y/n: n
Please enter a file name: test.dat
File saved
After running the above code, a file named test.dat should have
been created that contains a single Dictionary object containing
following key/value pairs:
ABCD, 012345
ADDE, 012340
Program Code Screenshot
Sample Output
Program Code to Copy
d = {}
while True:
#Prompt for product code
code = input('Enter a product code (four capital letters): ')
#Keep prompting until valid code is entered
while (len(code) is not 4) or not code.isupper():
code = input('That was not a correct product code, please try
again: ')
#Prompt product number
num = input('Enter a product number (a number with a leading 0):
')
#Keep prompting util a valid number is entered
while (not num.isdecimal()) or (num[0] is not '0'):
num = input('That was not a correct product number, please try
again: ')
#Store in dictionary
d[code] = num
#Prompt if user wants to add another product
ch = input('Do you wish to continue? Enter y/n: ')
if ch is not 'y':
break
#Open file
name = input('Please enter a file name: ')
f= open(name,'w')
#Write all dictionary items to file
for key,val in d.items():
f.write(key+','+val+'\n')
f.flush()
f.close()
print('File saved')
test.dat