Programs That Write to Files

This code writes to a file called 'receipt.txt' in the current folder. The 'w' means 'write'.

The with statement is the best way to open a file, because it automatically closes the file afterward. You could also do this, though:

f = open('receipt.txt', mode='w')
f.write("+---------------------+\n")
# etc
f.close()

But nobody does that anymore.

receiptrevisited.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from __future__ import print_function

def main():
    with open('receipt.txt', mode='w') as f:
        f.write("+------------------------+\n")
        f.write("|                        |\n")
        f.write("|      CORNER STORE      |\n")
        f.write("|                        |\n")
        f.write("| 2017-02-18  04:38PM    |\n")
        f.write("|                        |\n")
        f.write("| Gallons:       12.464  |\n")
        f.write("| Price/gallon: $ 3.459  |\n")
        f.write("|                        |\n")
        f.write("| Fuel total:  $ 43.11   |\n")
        f.write("|                        |\n")
        f.write("+------------------------+\n")


if __name__ == "__main__":
    main()

What You Should See


There's no visible output, but it should write to a file anyway.

Study Drills

  1. Hey, you know how to work with variables! Pick a price per gallon and put it into a float variable, then let the human enter in how many gallons of gas they want. Figure out the total cost. Then print the receipt to the file, but substitute their details so the file will look different depending on what they put in. I would remove the bars on the right side of the receipt, since making things line up would be hard.



©2017 Graham Mitchell