Page 243 - Beginning Programming with Pyth - John Paul Mueller
P. 243
3. Typeprint(os.getcwd())andclickRunCell.
You see the current working directory (cwd) that Python uses to obtain local code.
4. Inanewcell,typeforentryinos.listdir():print(entry)andclickRunCell.
You see a listing of the directory entries. The listing lets you determine whether the file you need is in the cwd. If not, you need to change directories to a location that does contain the required file.
os.chdir()
Using the import statement
The import statement is the most common method for importing a package into Python. This approach is fast and ensures that the entire package is ready for use. The following steps get you started using the import statement.
1. Open a new notebook.
You can also use the downloadable source file,
BPPD_11_Interacting_with_Packages.ipynb.
2. Change directories, if necessary, to the downloadable source code directory.
Generally, Notebook places you in the correct directory to use the source code files, so you won't need to perform this step. See the instructions found in the “Interacting with the current Python directory” sidebar.
3. Type import BPPD_11_Packages and press Enter.
This instruction tells Python to import the contents of the BPPD_11_Packages.py file that you created in the “Creating Code Groupings” section of the chapter. The entire library is now ready for use.
It’s important to know that Python also creates a cache of the package in the __pycache__ subdirectory. If you look into your
To change directories to a new location, you use the
method and include the new
location as a string, such as
os.chdir('C:\MyDir')
. However, you normally find with Notebook
that the cwd does contain the files for your current project.