Interface the Cake program to files
Now, let’s say we want to make the cake program more versatile that it can process the cake orders as a “batch” – archive from computer storage and generate the document for ingredients required to fill the cake orders.
Part 1 – Write the ingredients list to a file (10 points)
Option 1 – Your Lab 5 work with no problem:
Modify the program you developed for Lab 5 to make it output the data in the same format to a text file cake_ingredients_list.txt
Option 2 – Your Lab 5 still has functionality problem:
Modify the template given here (To Be Posted) to get the sentinel while loop working first, then make it to output the data in the same format to a text file cake_ingredients_list.txt
Note:Writing to a file is easier to code, so let’s do that first.
Hints:After the file has been opened, call the .write() function to write one line at a time to the file, in almost the exact fashion as calling print(). The difference is that the .write() function won’t place a new line feed to the end automatically like print(), soan explicit “n” has to be added(concatenated) to the end of the current line of data to be output.And, please read the code example from the bottom of Module 7.2 : write_a_single_line_to_file.py
Part 2 – Read the cake orders list from a text file (10 points)
Modify the program further to make it read a text file to input the cake orders. Or, if you want to leave Part 1 alone and/or not confident about your Part 1, then just do Part 2 in a different program. And, if you didn’t integrate the two, you have to submit TWO .py files – one for Part 1 and Part 2.
The data file that contains the orders has this format, for each line:
[1 character: cake type] [ 3 white spaces] [ 1 character: cake size ]
means: Red Velvet; Large
You are welcome to use any scheme you see fit to read and process the raw data from the file. Or, follow the suggestion below.
Hint: Use .read(n) to read n characters at a time. Specifically, for each line, cake order:
1) read 1 character to get the cake type(1, 2 or 3);
2) read 3 characters(white spaces) and then discard them, in order to move the read queue up;
3) read 1 character to get the cake size(L or R);
4) read 1 character(‘n’), and discard it; Then repeat for the next line, and so forth – all the way until no more character left, meaning when the last read gives ”(no character, two single quotes), which would be the sentinel like this:
while char != ”:
Code example download:
file_input = open(“data.txt”)
cake_char = file_input.read(1)
print(“cake_code: “, cake_char)
cake_num = eval(cake_char)
print(“ck_num**2 = “, cake_num**2)
spaces = file_input.read(3)
print(“delimiter – spaces: “%s”””” % spaces)