Question

In: Computer Science

Instructions In this exercise, you will use Python to complete four practical challenges: Creating 24 directories...

Instructions

In this exercise, you will use Python to complete four practical challenges:

  • Creating 24 directories for each week of class, each containing 3 folders for each day of class
  • Copying files from ~/Downloads into the current directory
  • Adding the copy script to the PATH
  • Add an alias for the copy script to ~/.bashrc

Class Notes Folder

Create a script called create_notes_drs.py. In the file, define and call a function called main that does the following:

  • Creates a directory called CyberSecurity-Notes in the current working directory
  • Within the CyberSecurity-Notes directory, creates 24 sub-directories (sub-folders), called Week 1, Week 2, Week 3, and so on until up through Week 24
  • Within each week directory, create 3 sub-directories, called Day 1, Day 2, and Day 3

Bonus Challenge: Add a conditional statement to abort the script if the directory CyberSecurity-Notes already exists.

Copying Student Exercises

So far you've used a few different Python modules, but for the rest of the homework, you will need to familiarize yourself with a new one. The shutil module is a Python module used for high-level file operations like moving and copying. Read this beforehand to get familiar with shutil and make sure to use the documentation while you're working through the homework.

Create a script called copy_activities.py with a function called stu_activities that does the following:

  • Finds files in ~/Downloads that contain the string Stu_
  • Copies these files into the current working directory

Note: This isn't just a challenge to complete for the sake of it, this is a practical script you can run to move any downloaded files from class into your class notes directories.

Copy Class Slides

Create a script called copy_slides.py with a function called pptx_copy Students will create a script that does the following:

  • Finds files in ~/Downloads with the file extension .pptx or .ppt
  • Copies these files into the current working directory

Note: This is another practical script you can use to move downloaded slides from class into your class notes directories.

Updating PATH and Add an Alias

Note: Consider this a bonus. You do not need to complete this step for credit. But, these tools will come up in class later, so you're strongly encouraged to study up now!

Now these great scripts have been written, but they are only executable from their relative path - where the files are in your system. In this final step, we'll make them accessible to you anywhere in your system directory.

  • First, read the following article to learn more about .bashrc, PATH, aliases, and the export command and answer the following questions.
    • What is the main difference betweeen ~/.bashrc and the ~/.bash_profile?
    • What does the export PATH command do?
    • What is the benefit of creating aliases?
  • Create a directory called /usr/local/bin and move your three scripts into this directory.
  • Update your .bashrc to add the directory /usr/local/bin to PATH with the following command:
export PATH=$PATH:/usr/local/bin
  • Finally create aliases in .bashrc for the three scripts
    • alias copy_activities="copy_activities.py"
    • alias copy_slides="copy_slides.py"
    • alias create_notes_drs="create_notes_drs.py"

Solutions

Expert Solution

What is the main difference betweeen ~/.bashrc and the ~/.bash_profile?
.bash_profile is executed for login shells, while .bashrc is executed for interactive non-login shells.

What does the export PATH command do?
Export command marks an environment variable to be exported with any newly forked child processes and
thus it allows a child process to inherit all marked variables.

What is the benefit of creating aliases?
• It eliminates the need to manage multiple email addresses for a single website.
• With it, you don’t need to create new email addresses.

Add scripts to bash file.

  • alias copy_activities="copy_activities.py"
  • alias copy_slides="copy_slides.py"
  • alias create_notes_drs="create_notes_drs.py"

create_notes_drs.py

import os, errno

def createDirectory(path, k=24):
    week = "Week"
    for w in range(1, k+1):
        weekPath = path+"/"+week+" "+str(w)
        os.makedirs(weekPath, exist_ok=True)
        for d in range(1, 4):
            day = "Day"
            os.makedirs(weekPath+"/"+day+" "+str(d), exist_ok=True)

def main():
    directory = "CyberSecurity-Notes"
    dir = os.path.exists(directory)
    if not dir:
        try:
            os.makedirs(directory)
            createDirectory(directory)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise Exception("unable to create dir")
    else:
        raise Exception("Directory already exist!")
main()

copy_activities.py

import os, fnmatch
import shutil

def stu_activities():
    downloadsPath = os.path.os.path.expanduser("~")+"/Downloads/"
    ls = fnmatch.filter(os.listdir(downloadsPath), 'Stu_*')
    for i in ls:
        shutil.copyfile(downloadsPath+"/"+i, "./"+i)  
stu_activities()

copy_slides.py

import os, fnmatch
import shutil

def pptx_copy():
    downloadsPath = os.path.os.path.expanduser("~")+"/Downloads/"
    lsPDF = fnmatch.filter(os.listdir(downloadsPath), '*.pptx')
    lsPEM = fnmatch.filter(os.listdir(downloadsPath), '*.ppt')
    totalFiles = lsPDF+lsPEM
    for i in totalFiles:
        shutil.copyfile(downloadsPath+"/"+i, "./"+i)
    return   
pptx_copy()



Related Solutions

This is an exercise on basic python grammar. Instructions Assume there are 10 teams in a...
This is an exercise on basic python grammar. Instructions Assume there are 10 teams in a competition. Their names are "team1", "team2" .. "team10". Write a function to generate their order of performance randomly. Submit your code in Jupyter notebook format (.ipynb) on Canvas Hint Use a list to save all the team names Define a function called order()   Use built-in module random to generate a random index within the list Remove the item from the current list and add...
To complete this comprehensive exercise, use the Excel spreadsheet program. In this exercise you will be...
To complete this comprehensive exercise, use the Excel spreadsheet program. In this exercise you will be using linear programming and Solver in Excel to solve the problem described in the following scenario. At Goodman Shipping, the load master wants to determine the mix of cargo to be carried on the next trip. The ship's volume limit for cargo is 100,000 cubic meters, and its weight capacity is 2,310 tons. The master has five different types of cargo from which to...
DIRECTIONS: Complete the following Programming Exercise in Python. Name the file Lastname_Firstname_E1. You just started your...
DIRECTIONS: Complete the following Programming Exercise in Python. Name the file Lastname_Firstname_E1. You just started your summer internship with ImmunityPlus based in La Crosse, Wisconsin. You are working with the forecasting team to estimate how many doses of an immunization drug will be needed. For each drug estimation, you will be provided the following information: corona.txt 39 20 31 10 42 49 54 21 70 40 47 60 - The size of the target population. - The life expectancy, in...
instructions- You have to use Python in order to do this Problem Set. 4 Cobb-Douglas Production...
instructions- You have to use Python in order to do this Problem Set. 4 Cobb-Douglas Production Function Suppose a firm uses the following production function Y = z × K0.3 × N 0.7 d , where Y is output, z is TFP, K is capital, and Nd is labor. 1. Set z = 10, K = 5 and plot the production function over the range Nd ∈ [0, 5] 2. Derive this function w.r.t. Nd.Set z = 10, K =...
Exercise: Anthropometrics Assessment Instructions: Complete the following measurements with your partner. Calculate the BMI of a...
Exercise: Anthropometrics Assessment Instructions: Complete the following measurements with your partner. Calculate the BMI of a female who is 66 inches (5 foot 6 inches) and 170 lb. What is the BMI classification? (BMI = weight in kg/height in meters squared (m2); weight in kg = weight in lb./2.2; height in meters = height in inches x 2.54 cm; height in meters = height in cm/100). *Remember to square the meters value in the denominator. Example: Height = 60 inches...
Reflection Paper Instructions Complete the following by writing a response to three of the four following...
Reflection Paper Instructions Complete the following by writing a response to three of the four following questions. For each question, your response should be 2 or more paragraphs. Make it clear which question you are answering and use correct grammar throughout. If you answer all four questions, only the first three provided will be graded. 1. Describe how you could use hypothesis testing to help make a decision in your current job, a past job, or a life situation. Include...
Cryptography - please use Python to complete the following task. You don't have to implement AES...
Cryptography - please use Python to complete the following task. You don't have to implement AES just import the necessary libraries. Can you fix my code? Thanks! Read in a 128 bit key from the user (16 characters). If the user enters a key of any other size it's fine to terminate the program with an error. Read in a string of arbitary length from the user. (ie, the string could be 1 character, or 50,000, or anywhere in between)....
Please analyze and create a starter code in Python using spaCy, that can demonstrate practical use...
Please analyze and create a starter code in Python using spaCy, that can demonstrate practical use of the package. Also give a brief explanation of what the purpose of the spaCy package is. Please use 3 different methods such as a loop statement, if statement, tuples, lists etc. Please provide detailed comments on each line of code. Please explain the purpose of the method used. Please write and run your code example.
In detail discuss, with the use of practical examples, FOUR (4) management styles and the potential...
In detail discuss, with the use of practical examples, FOUR (4) management styles and the potential impact each style may have on a business.
PYTHON Exercise: Accelerate Method ------------------------- ### Description In this exercise, you will add to your `Car`...
PYTHON Exercise: Accelerate Method ------------------------- ### Description In this exercise, you will add to your `Car` class a method to accelerate the speed of an instance. ### Class Name `Car` ### Method `accelerate()` ### Parameters * `self` : the `Car` object to use * `delta_speed` : a number, the desired value to add to the speed data member. ### Action Adds `delta_speed` to the speed of the object. If the new speed is too fast, then set the speed to...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT