Interact with the Directory Structure - dummies

By John Paul Mueller

To find files and interact with them on a system, you need to work with the directory structure. This means working with the structure using Python-specific calls so that your code works on every platform you need to support. Fortunately, you don’t have to do anything special to get this feature to work. Python includes all the functionality required, as demonstrated in the following steps:

1Open a copy of the Python Shell.

You see the Python Shell window.

2Type the following code (pressing Enter after each line):

import os, sys, stat, time
BP4D = os.listdir("C:BP4D")

Python imports the required modules, places a directory listing in BP4D, and then displays the resulting list onscreen. You must change the path of C:BP4D to the storage location on your system as necessary. The listdir() function obtains a list of files and directories in whatever path you specify.

3Type the following code (pressing Enter after each line):

Chap04 = os.path.join("C:BP4D", BP4D[0])

You see a combined path that points to the directory, which in this case is C:BP4DChapter04. The join() function is invaluable in creating new directories based on queries that you make to the file system.

4Type the following code (pressing Enter after each line):

Chap04Mode = os.stat(Chap04).st_mode

The first line of code asks for the statistics for the path represented by Chap04. It then obtains a single statistic, st_mode. The st_mode value defines what sort of entry Chap04 is. You can use features of the stat module to obtain additional information, such as whether the entry is a directory. The documentation at Python stat module tells you quite a lot more about the stat module.

5Type the following code (pressing Enter after each line):

Chap04Content = os.listdir(Chap04)
FirstFile = os.path.join(Chap04, Chap04Content[0])
FirstFileStat = os.stat(FirstFile)

This series of code entries begins by getting the content of the C:BP4DChapter04 directory. It then creates a path to the first file in that directory and obtains the statistics for that file. Given that the C:BP4DChapter04 directory contains only files and not other directories, the stat.S_ISREG() check should return True.

6Type print(FirstFileStat.st_size) and press Enter.

Many of the statistics are directly accessible. In this case, you see the size of the file.

7Type print(time.ctime(FirstFileStat.st_mtime)) and press Enter.

Some statistics, such as the last modification date, will require conversion before you can read them. In this case, you use the time.ctime() function to change the number of ticks reported by st_mtime into an actual date and time.

8Close the Python Shell.

You’re all done.