1. The create_python_script function creates a new python script in the current working directory, adds the line of comments to it declared by the ‘comments’ variable, and returns the size of the new file. Fill in the gaps to create a script called “program.py”.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
1. The create_python_script function creates a new python script in the current working directory, adds the line of comments to it declared by the ‘comments’ variable, and returns the size of the new file. Fill in the gaps to create a script called “program.py”.
- import os
def create_python_script(filename):
comments = “# Start of a new Python program”
withopen(filename, ‘a+’) as f:
f.write(comments)
print(f.read())
filesize = os.path.getsize(filename)
return(filesize)
print(create_python_script(“program.py”))
2. The new_directory function creates a new directory inside the current working directory, then creates a new empty file inside the new directory, and returns the list of files in that directory. Fill in the gaps to create a file “script.py” in the directory “PythonPrograms”.
- import os
def new_directory(directory, filename):
# Before creating a new directory, check to see if it already exists
ifnot os.path.exists(directory):
os.mkdir(directory)
name=os.path.join(directory, filename)
file=open(name,’w’)
file.close()
return os.listdir(directory)
# Create the new file inside of the new directory
# Return the list of files in the new directory
print(new_directory(“PythonPrograms”, “script.py”))
3. Which of the following methods from the os module will create a new directory?
- path.isdir()
- listdir()
- mkdir()
- chdir()
4. The file_date function creates a new file in the current working directory, checks the date that the file was modified, and returns just the date portion of the timestamp in the format of yyyy-mm-dd. Fill in the gaps to create a file called “newfile.txt” and check the date that it was modified.
- import os
import datetime
def file_date(filename):
# Create the file in the current directory
withopen (filename,’w’) asfile:
pass
timestamp = os.path.getmtime(filename)
c=datetime.datetime.fromtimestamp(timestamp)
# Convert the timestamp into a readable format, then into a string
# Return just the date portion
# Hint: how many characters are in “yyyy-mm-dd”?
return (“{}”.format(c.strftime(“%Y-%m-%d”)))
print(file_date(“newfile.txt”))
# Should be today’s date in the format of yyyy-mm-dd
5. The parent_directory function returns the name of the directory that’s located just above the current working directory. Remember that ‘..’ is a relative path alias that means “go up to the parent directory”. Fill in the gaps to complete this function.
- import os
def parent_directory():
# Create a relative path to the parent
# of the current working directory
relative_parent = os.path.join(os.getcwd(), os.pardir)
# Return the absolute path of the parent directory
return os.path.abspath(relative_parent)
print(parent_directory())
6. We’re working with a list of flowers and some information about each one. The create_file function writes this information to a CSV file. The contents_of_file function reads this file into records and returns the information in a nicely formatted block. Fill in the gaps of the contents_of_file function to turn the data in the CSV file into a dictionary using DictReader.
import os
import csv
# Create a file with data in it
def create_file(filename):
with open(filename, “w”) as file:
file.write(“name,color,type\n”)
file.write(“carnation,pink,annual\n”)
file.write(“daffodil,yellow,perennial\n”)
file.write(“iris,blue,perennial\n”)
file.write(“poinsettia,red,perennial\n”)
file.write(“sunflower,yellow,annual\n”)
# Read the file contents and format the information about each row
def contents_of_file(filename):
return_string = “”
# Call the function to create the file
create_file(filename)
# Open the file
with open(filename) as file:
# Read the rows of the file into a dictionary
f = csv.DictReader(file)
# Process each item of the dictionary
for row in f:
return_string += “a {} {} is {}\n”.format(row[“color”], row[“name”], row[“type”])
return return_string
#Call the function
print(contents_of_file(“flowers.csv”))
- # Read the file contents and format the information about each row
def contents_of_file(filename):
return_string = “”
# Call the function to create the file
create_file(filename)
# Open the file
with open(filename) as file:
# Read the rows of the file into a dictionary
reader = csv.DictReader(file)
# Process each item of the dictionary
for row in reader:
return_string += “a {} {} is {}\n”.format(row[“color”], row[“name”], row[“type”])
return return_string
7. Using the CSV file of flowers again, fill in the gaps of the contents_of_file function to process the data without turning it into a dictionary. How do you skip over the header record with the field names?
import os
import csv
# Create a file with data in it
def create_file(filename):
with open(filename, “w”) as file:
file.write(“name,color,type\n”)
file.write(“carnation,pink,annual\n”)
file.write(“daffodil,yellow,perennial\n”)
file.write(“iris,blue,perennial\n”)
file.write(“poinsettia,red,perennial\n”)
file.write(“sunflower,yellow,annual\n”)
# Read the file contents and format the information about each row
def contents_of_file(filename):
return_string = “”
# Call the function to create the file
create_file(filename)
# Open the file
with open(filename, ‘r’) as f:
# Read the rows of the file
rows = csv.reader(f)
# Skips the headers
next(rows)
# Process each row
for row in rows:
name, color, typeflower = row
# Format the return string for data rows only
return_string += “a {} {} is {}\n”.format(color, name, typeflower)
return return_string
#Call the function
print(contents_of_file(“flowers.csv”))
- import os
import csv
# Create a file with data in it
def create_file(filename):
withopen(filename, “w”) asfile:
file.write(“name,color,type\n”)
file.write(“carnation,pink,annual\n”)
file.write(“daffodil,yellow,perennial\n”)
file.write(“iris,blue,perennial\n”)
file.write(“poinsettia,red,perennial\n”)
file.write(“sunflower,yellow,annual\n”)
# Read the file contents and format the information about each row
def contents_of_file(filename):
return_string = “”
# Call the function to create the file
create_file(filename)
# Open the file
withopen(filename, ‘r’) as f:
# Read the rows of the file
rows = csv.reader(f)
# Skip the header row
next(rows)
# Process each row
for row in rows:
# Extract the values from the row
name, color, flower_type = row
# Format the return string for data rows only
return_string += “a {} {} is {}\n”.format(color, name, flower_type)
return return_string
# Call the function
print(contents_of_file(“flowers.csv”))
8. In order to use the writerows() function of DictWriter() to write a list of dictionaries to each line of a CSV file, what steps should we take? (Check all that apply)
- Create an instance of the DictWriter() class
- Write the fieldnames parameter into the first row using writeheader()
- Open the csv file using with open
- Import the OS module
9. Which of the following is true about unpacking values into variables when reading rows of a CSV file? (Check all that apply
- We need the same amount of variables as there are columns of data in the CSV
- Rows can be read using both csv.reader and csv.DictReader
- An instance of the reader class must be created first
- The CSV file does not have to be explicitly opened
10. If we are analyzing a file’s contents to correctly structure its data, what action are we performing on the file?
- Writing
- Appending
- Parsing
- Reading