<<

Unit III - focuses on using Python to develop sustainable code. In this unit students will be working with Python Modules, Powerful Statements, Methods and Structures for Robust Code, and Proper Functions. Students will be introduced to data structures and files in Python 3 and be ready for more-advanced Python learning. Module I – Python Modules Students will be able to:

.platform • Identify the platform running a • os: os.getcwd, os.chdir, os.listdir, Python script ('Linux', 'win32', os., os., os.rename 'Darwin') • os.: os.path.abspath, • Get the current working os.path.exists, os.path.isfile, • Change the current os.path.isdir • List the content of the current working directory • Create a new directory • Remove a directory • Rename files and directories • Recognize the difference between relative and absolute paths • Test whether a path exists • Test whether a specific file or directory exists

Activity 4 – File System 1. Open Your IDE of (Notebooks.Azzure, repl.It or Visual Studio) 2. Open a New Project 3. Name it U3_M1_A4-XX (XX represents your first initial and last name I.E Mjordan). 4. Insert your program comments. 5. Insert a line comment to identify each step.

Concept: Platform Identification 6. View this video – Using the sys module

In recent years, when you reach the download page of a website, you are directed to download a file that matches your . For example, when using a Windows computer, download links direct you to .exe files; similarly, when using a Mac, you download links direct you to .dmg files. This code awareness makes the user experience more pleasant.

Python scripts can run on different platforms, including Windows, Mac, and Linux. The sys module provides access to several system variables, including the platform. If you know the platform your Python code is running on, you may be able to change the behavior of your application to accommodate that platform. Examples

Identifying the platform 7. import sys

(sys.platform)

Concept: Directory Operations 8. View This Video – Directory Operations

Most operating systems organize files in hierarchical structures. For example, directories (also known as folders) may contain other directories and files. The Python os module contains some useful functions to navigate and manipulate files and directories. In the following sections, you will see how to perform some basic directory operations.

Finding and changing the current working directory

When navigating the hierarchical file system, you will always be located in a directory. The directory you're in is referred to as the "current working directory", or "cwd" for short. Python's os.getcwd() nethod returns a string containing the current working directory path.

The working directory can be changed in Python using os.chdir(path), changes the cwd into path, which is a string variable containing a path to the new working directory.

NOTE: When changing a working directory, you can specify .. as your path. This effectively changes the working directory one level up into the parent directory.

Listing the content of a directory

You might need to access or read the content of a directory. The os.listdir() method returns a list of the files and directories in the current working directory.

Creating and removing directories

In Python, a new directory can be created manually using os.mkdir(path), where path is the path and name of the new directory. Similarly, a directory can be removed using os.rmdir(path), where path is the name of the directory to be deleted. Note that rmdir can delete only empty directories; if the directory specified by path is not empty, an error will be raised.

Renaming files and directories

Many tasks can be automated by Python. For example, if you want to rename a large number of files to match a predefined pattern, you can use Python's os.rename(src, dst) method, in which src is a string containing the path of a source file or directory, and dst is a string containing the new (destination) path and/or name.

Examples

Directory structure

The examples in this lesson traverse through the following directory structure. parent_dir

|__ child1_dir

| |

| |_ leaf1.txt

|

|__ child2_dir

| |

| |_ leaf2.txt

|

|__ parent_leaf.txt

|

|__ text_file.txt

Directories

The directories in this structure are parent_dir, child1_dir, and child2_dir.

Files

The files in this structure are leaf1.txt, leaf2.txt, parent_leaf.txt, and text_file.txt. Working directory

In this example, you will change the current working directory to parent_dir, then to child1_dir, then back to parent_dir. You will also see a printout of the current working directory every step.

9. import os # Change the current working directory to parent os.chdir('parent_dir') print('Changed working dir to parent: ', os.getcwd()) # Change the current working directory to child1 dir os.chdir('child1_dir') print('Changed working dir to child1: ', os.getcwd()) # Change the current working directory back to the parent dir os.chdir('..') print('Changed working dir back to parent: ', os.getcwd()) Directory content

In this example, you will list the content of the current working directory (parent_dir).

10. import os

# Print the current working directory (should be "parent_dir") print('The current working directory is:', os.getcwd())

# List the content of the directory (both files and other directories) print('Current directory content: ', os.listdir()) Creating and removing directories

In this example, you will create and remove directories.

11. import os

# Print the current working directory (should be "parent_dir") print('The current working directory is:', os.getcwd())

# Create a new directory os.mkdir('new_child') print('Created new_child dir')

# List the content of the directory print('Current directory content: ', os.listdir())

# Remove the new child directory os.rmdir('new_child') print('Removed new_child dir')

# List the content of the directory print('Current directory content: ', os.listdir())

Renaming directories

In this example, you will create a new directory, and then change its name.

12. import os

# Print the current working directory (should be "parent_dir") print('The current working directory is:', os.getcwd())

# Create a new directory os.mkdir('new_child') print('Created new_child dir')

# List the content of the directory print('Current directory content:', os.listdir())

# Rename new_child as old_child os.rename('new_child', 'old_child') print('Renamed new_child as old_child') # List the content of the dir print('Current directory content: ', os.listdir())

# Remove the old_child dir os.rmdir('old_child') print('Removed old_child dir') print('Current directory content: ', os.listdir())

Task 1: Directory Operations 13. Write a program to: • Prompt the user for a directory name • Create the directory • Verify the directory was created by listing the content of the current working directory • Remove the created directory • Verify the directory was removed by listing the contents of the current working directory • Import os • Create a variable dirName = and ask for user input to enter a directory name • Print dirName • Use mkdir to os and include dirName • Print a complete sentence stating the current directory content, using .listdir() on os • Print a complete sentence stating removal of dirName using rmdir() on os • Print a complete sentence stating the current directory content, using .listdir() on os

14. Write a program to: • Create a directory called "myDir" • Change the current working directory to "myDir" • Verify you are in the correct directory by displaying the current working directory • Change the working directory back to the parent directory • Verify you are in the correct directory by displaying the current working directory • Rename "myDir" to "yourDir" • Verify the directory was renamed by listing the content of the current working directory • Remove "yourDir" • Verify the directory was removed by listing the content of the current working directory • Import os • Write a statement stating you are making myDir • Use mkdir() on os to make “myDir) • Print a statement to notify changing working directory • Use .chdir to change working directory to myDir • Display the current working directory • Use a print statement to state the current working directory • Use .getcwd() • Print a statement to notify changing working directory • Use chdir() to get back to parent directory • Display the current working directory • Use a print statement to state the current working directory • Use .getcwd() • Print a statement notifying change of myDir to yourDir • Use .rename() to rename myDir • Use a print statement to verify current directory content • Use .listdir() • Write a print statement to remove yourDir • Use rmdir() to remove yourDir • Use a print statement to verify current directory content • Use .listdir() Concept: Path Operations 15. View This Video – Path Operations

Relative and absolute paths

A file or directory has a name and a path, which is just a roadmap to its specific location in the file system. Most operating systems, support two types of paths:

• Relative paths: path to a file or directory from a specific location (or current working directory) • Absolute paths: path to a file or directory from a root. In flavors, a root is "/"; whereas, on Windows machines a root is ":\"

For example, consider the UNIX directory structure we have been manipulating:

/

|

|__ parent_dir

|

|__ child1_dir

| |

| |_ leaf1.txt

|

|__ child2_dir

| |

| |_ leaf2.txt

|

|__ parent_leaf.txt

|

|__ text_file.txt

If you are currently in parent_dir and trying to get to leaf1.txt, the relative path would be (child1_dir/leaf1.txt). It's a relative path because it is relative to your current location.

The absolute path to leaf1.txt is (/parent_dir/child1_dir/leaf1.txt), it starts from the root "/" all the way to the destination file. It's absolute because it starts from the absolute root.

In Python, you can use relative or absolute paths; however, it might be useful to a relative path into an absolute path using the function os.path.abspath(path). The function returns a string containing the absolute path to a file or directory specified by the relative path passed as an argument.

In [1]: import os.path

In [2]: os.path.abspath('child1_dir/leaf1.txt')

Out[2]: '/parent_dir/child1_dir/leaf1.txt'

Testing the existence of paths, files, and directories

The module os.path contains common pathname manipulation functions. For example, os.path.exists(path) tests whether path(relative or absolute) exists in the file system, os.path.isfile(path)returns True if path (relative or absolute) refers to an existing file, and os.path.isdir(path) returns True if path refers to an existing directory. Other functions in the module allow you to get the size of a file, split and join path names regardless of the operating system, and so on. The Python Documentation site at https://docs.python.org/3/library/os.path.html has more information on the os.path module.

NOTE: In UNIX systems, paths are written using a forward slash (/) as separators; however, on Windows systems, paths are written using backslashes (\) as separators. When joining path names, use os.path.join and Python will use the appropriate separator for the platform running the script.

Examples In this example, you will get the absolute path to a file and test whther the path exists and if it refers to a file or a directory.

16. # Print the current working directory (should be "parent_dir") print('The current working directory is:', os.getcwd())

# the absolute path to child1_dir/leaf1.txt abs_path = os.path.abspath('child1_dir/leaf1.txt') print("Absolute path to leaf1.txt is: ", abs_path)

# Test whether the path exists if(os.path.exists(abs_path)): print("Path exists")

# Test to see if it's a file or directory if(os.path.isfile(abs_path)): print("It's a file") elif (os.path.isdir(abs_path)): print("It's a dir")

else: print("Path doesn't exist")

Task 2: Path Operations 17. Write a program that prompts the user for a file or directory name, then prints a message verifying if it exists in the current working directory. • Import os.path • Create variable name ask for user input to enter a file or directory name • Use an if statement to see if os.path.exists • Print that the file or directory exists in the current working directory • Or print that the file or directory does NOT exist in the current working directory 18. Write a program to print the absolute path of all directories in parentDir • Hints: • Verify you are inside parentDir using os.getcwd() • Use os.listdir() to get a list of files and directories in parentDir • Iterate over the elements of the list and print the absolute paths of all the directories • Import os, os.path • Hint 1 1) Use a print statement to state the current working directory • Hint 2 1) Create a variable named filesDirList • Hint 3 1) Iterate for element in variable created in hint 2 • If (os.path.isdir(element)) • Then print the abspath of element