We write and execute the simplest program that will create a data file on disk.
Till now, it was not required to store any data on our hard drive or a USB memory stick. Now we work through a series of simple exercises in storing and retrieving data in files on storage media. Then we use these methods to save and edit Tkinter lines in a practical way. Tkinter lines can be a large collection of separate line segments and shapes. If we are developing a drawing of complexity and richness, it is vital that we be able to store and retrieve work in progress.
Write, save, and execute the program shown in the usual way. When you run the program, all you will observe from a successful execution is a short pause after you have clicked Enter. The execution will terminate without any messages. However, a new file called brand_new_file.dat
now exists on the destination directory constr
. We should open constr
and verify that this is indeed the case.
# file_make_1 .py # >>>>>>>>>>>>>> filename = "constr/brand_new_file.dat" FILE = open(filename,"w")
This minimalist-looking program achieves the following objectives:
Once a file has been created, it can then be read. So a program to read an existing file on disk would be:
# file_read_1 .py # >>>>>>>>>>> filename = "constr/brand_new_file.dat" FILE = open(filename,"r")
As you can see, the only difference is the r
instead of the w
.
Note that Python reads and writes files in more than one format. A b
as in rb
and wb
reads and writes as byte or binary format. These are the 1s
and 0s
in each byte. r
and w
without the b
as in our examples tells the Python interpreter that it must interpret the bytes as ASCII characters. The only point we need to remember is to keep the formats separate.
18.191.139.169