Creation of a new file on a hard drive

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.

How to do it...

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")

How it works...

This minimalist-looking program achieves the following objectives:

  • It verifies that Python's file IO functions are present and working. No modules need to be imported
  • It demonstrates that there is nothing unusual about the way Python accesses data files on storage devices
  • It proves that the operating system obeys file creation directives from Python

How to read the newly created file

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.139.169