In this lesson, you'll learn how to use Python's csv module to convert your dictionary data to a common file format and save it so that you'll be able to retrieve it later on.
Before using the csv module, however, you'll learn a common shortcut when writing to or reading from files with Python.
Python with - Context Manager
You've already learned how to interact with a file using the open() function and the .close() method.
When you're working with files, you might often run into some unexpected errors. Sometimes, the contents of the file are not what you expect, or the file doesn't even exist at all. You want to be sure that the file object you opened will be closed in any case. You can achieve this by using a context manager when opening the file:
with open("filecounts.txt", "r") as file_in:
print(file_in.read())
Using the above construct with the with keyword, which is called a context manager, you'll automatically close the file object after the indented part of your code is done running.
Python knows how to close the file safely once it reaches the end of the indented code block.
Info: You'll most often see a context manager when you're working with files, and it's encouraged to use them over the three-step process described in the previous lessons.
The with context manager is a convenient and safe way to handle your file interactions. You can use it in the same way when writing to a file.
CSV File Creation
Now you'll use the context manager and the csv module to save your file counter output to a .csv file so that it's in a format that'll be accessible to other developers:
import csv
# -- snip --
count = {"": 8, ".csv": 2, ".md": 2, ".png": 11}
with open("filecounts.csv", "a") as csvfile:
countwriter = csv.writer(csvfile)
data = [count[""], count[".csv"], count[".md"], count[".png"]]
countwriter.writerow(data)
Some parts of this code snippet will be unfamiliar, so you'll take a look at each line and read about what it does:
- First, you're importing the
csvmodule from Python's standard library. - Then you're using a context manager to open up a file in append mode (
"a") and save the file object to the variablecsvfile. - Next, you're creating a CSV writer object with the opened
csvfileas its input, and you save it to the variablecsvwriter. - Now, you're preparing the row of
datathat you want to write to the file. For this, you're accessing each piece of information through a dictionary lookup and adding them to a list. - file_inally, you're using the
csvwriterto write the row ofdatato your file using.writerow().
As you can see, the process is similar to when you were writing plain text to a file before.
CSV Module Practise
- Run your script and check the output. What does it write to your file?
- Run the script a second time and check the output.
- Rewrite the functionality of the script without using the
csvmodule. Create the correct formatting only with proper string formatting. - What are the advantages of using the csv module over plain string formatting? What do you think is missing from your output file? How could you add it? Explore the
csvmodule's documentation.
Data Storage Formats
CSV stands for comma-separated values and is a relatively straightforward way to systematically format your data for storage. It relies on the idea behind tabular data with rows and columns and is a common export format for applications such as Microsoft Excel or Google Sheets.
Because CSV only separates values with commas, you can write your own CSV files even without using Python's csv module. However, the module introduces some quality-of-life improvements, such as adding headers and choosing between different flavors. It also prevents you from accidentally messing up the correct syntax.
Other formats for storing your data are more difficult to reproduce manually, which means that there are more opportunities to mess up the correct syntax. That's why it's a good idea to use the existing modules to help you create the right formatting, as well as read it back.
Later in this module, you'll also learn to work with JSON, a common format used for data exchange over the Internet.
In a future lesson, you'll learn how to read the data you saved back into your program so that you can work forward with it.
Summary: Python with - Context Manager
- You can use a context manager through the
withkeyword to safely open file objects, and rest assured that they'll be closed once your script exits the indented code block. - To create interchangeable data formats that follow certain syntax standards, you can use built-in libraries, such as the
csvmodule. It allows you to write data to a file following a pre-defile_ined syntax that sticks to the specifications of the data format you're creating.