WEEK 2:: PYTHON AUTOMATION MODIFY FILE DIRECTORIES, CSV FILES

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

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 with DictWriter() class (We have to create a DictWriter() object instance to work with, and pass to it the fieldnames parameter defined as a list of keys.) - Write the fieldnames parameter into the first row using writeheader() (The non-optional fieldnames parameter list values should be written to the first row.) - Open the csv file using using WITH OPEN (The CSV file has to be open before we can write to it.)

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 (We need to have the exact same amount of variables on the left side of the equals sign as the length of the sequence on the right side when unpacking rows into individual variables.) - Rows can be read using both csv.reader and csv.DictReader (Although they read the CSV rows into different datatypes, both csv.reader or csv.DictReader can be used to parse CSV files.) - An instance of the reader class must be created first (We have to create an instance of the reader class we are using before we can parse the CSV file.)

Some more functions of the os.path module include getsize() and isfile() which get information on the file size and determine if a file exists, respectively. In the following code snippet, what do you think will print if the file does not exist? import os file= "file.dat" if os.path.isfile(file): print(os.path.isfile(file)) print(os.path.getsize(file)) else: print(os.path.isfile(file)) print("File not found")

False File Not Found (Because the file does not exist, getsize() will never be called and our error message will be printed instead.)

What's the purpose of the os.path.join function?

It creates a string containing cross-platform concatenated directories. (By using os.path.join we can concatenate directories in a way that can be used with other os.path() functions.)

Which of the following must we do before using the csv.writer() function?

Open the file with write permissions. (The file must be open, preferably using with open() as, and write permissions must be given)

If we are analyzing a file's contents to correctly structure its data, what action are we performing on the file?

Parsing (Parsing a file means analyzing its contents to correctly structure the data. As long as we know what the data is, we can organize it in a way our script can use effectively.)

DictReader() allows us to convert the data in a CSV file into a standard dictionary. DictWriter() \ allows us to write data from a dictionary into a CSV file. What's one parameter we must pass in order for DictWriter() to write our dictionary to CSV format?

The fieldnames parameter of DictWriter() requires a list of keys (This will help DictWriter() organize the CSV rows properly.)

What happens to the previous contents of a file when we open it using "w" ("write" mode)?

The old contents get deleted as soon as we open the file. (When using write mode, the old contents get deleted as soon as the file is opened.)

What is the difference between the readline() and read() methods?

The readline() method reads a single line from the current position, the read() method reads from the current position until the end of the file. (Both methods read from the current position. The readline() method reads one line, while read() reads until the end of the file.)

How can we check if a file exists inside a Python script?

Using the os.path.exists function.

Which of the following lines would correctly interpret a CSV file called "file" using the CSV module? Assume that the CSV module has already been imported.

data=csv.reader(file) (The reader() function of the CSV module will interpret the file as a CSV.)

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" with open (filename,"w")as file: file.write(comments) filesize = len(comments) return(filesize) print(create_python_script("program.py")) (ans : 31)

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 if os.path.isdir(directory) == False: os.mkdir(directory) # Create the new file inside of the new directory os.chdir(directory) with open ("script.py", "w") as file: pass # Return the list of files in the new directory return os.listdir(os.getcwd()) print(new_directory("PythonPrograms", "script.py")) (ans: ['sript.py'])

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('..') # Return the absolute path of the parent directory return os.path.abspath(relative_parent) print(parent_directory()) (ans: / )

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 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 #Call the function print(contents_of_file("flowers.csv"))

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)as file: # Read the rows of the file rows = csv.DictReader(file) # Process each row for row in rows: name, color, type = row # Format the return string for data rows only return_string += "a {} {} is {}\n".format(row["color"], row["name"], row["type"]) return return_string #Call the function print(contents_of_file("flowers.csv"))

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 with open(filename,"w") as file: pass timestamp = os.path.getmtime(filename) # Convert the timestamp into a readable format, then into a string new_time=datetime.date.fromtimestamp(timestamp) # Return just the date portion # Hint: how many characters are in "yyyy-mm-dd"? return ("{}".format(new_time)) print(file_date("newfile.txt")) # Should be today's date in the format of yyyy-mm-dd (ans: 2020-06-23 or whatever date is when you run this)

Which of the following methods from the os module will create a new directory?

mkdir (os.mkdir() will create a new directory with the name provided as a string parameter.)

Can you identify which code snippet will correctly open a file and print lines one by one without whitespace?

with open("hello_world.txt") as text: for line in text: print(line.strip()) (Here, we are iterating line by line, and the strip() command is used to remove extra whitespace.)


Ensembles d'études connexes

Chapter 2 - Statistics and APA Ethical Guidelines

View Set

Chemistry: Heterocyclic compounds

View Set

CH 11 Aggregate Output, Price level and the Interest Rate

View Set

CRJ TEST 2 DR KUMAR BROCKPORT 6-7

View Set

chapter 23 vocabulary (Emergency Medical Procedures) study guide

View Set

Business Intelligence Systems Ch.1

View Set

The Nursing Curriculum in the Information Age

View Set