- 1
-
We define a string to use as our filename. The
.txtextension conventionally identifies a text file; Python’sopen()does not require it. - 2
-
The mode
'w'creates a file or immediately truncates an existing file to zero length.open()returns a file object, which we store inf. - 3
-
We can access a variety of methods attached to the file. The full list of methods is given in Table A.7, but a partial list is given below. In this case we use
write()to write the given text. - 4
-
Closing flushes buffered output and releases the file resource. Ordinary
open()does not generally lock a file against other programs; sharing and locking are separate matters.
6 Files and IO
Table of contents
Upon completion of this lesson you should:
- …appreciate the 2 main types of memory in a computer
- …be familiar with the file system, files, and folders
- …understand both relative and absolute file paths
- …know how to write simple text to a file, and read it back in
- …be able to format text to create desired output in files
- …be able to use the command line to perform basic tasks directly
- …know how to install external python libraries using the command line
6.1 Types of Memory
TED-Ed · about 5 min. An animated explanation of how temporary memory and long-term storage differ in speed, capacity, and persistence.
We have not talked much about how computers work internally. As we write more complicated computer programs we need to understand more about how the computer deals with data because it impacts performance. Examples of this trend are advanced numerical algorithms such as machine learning or climate modeling.
It is convenient to think of computer memory as being either permanent and slow or temporary and fast.
6.1.1 Permanent Memory
Computers commonly use a hard disk drive (HDD) or a solid-state drive (SSD) for long-term storage. Both retain data when power is removed, although neither lasts forever. Storage can be internal or external; some internal drives are replaceable, while others are built into the device. Several removable storage formats are shown in Figure 6.2.
Data is represented by bits, with values 0 and 1. Different devices store those bits differently:
- An HDD stores magnetic patterns on rotating platters. A moving head writes patterns and senses magnetic changes when reading.
- An SSD stores data electronically in flash-memory cells and has no moving parts. This makes them much more stable and faster.
- Optical discs such as CDs, DVDs, and Blu-ray discs use a laser to read differences in reflected light from the surface of the disk. Etching a pattern on the disk is information is stored.
Storage access is generally slow, so avoiding unnecessary file reads and writes can improve performance, but saving results is still essential when we need to keep them.
Github has taken long-term storage to a new level.
6.1.2 Temporary Memory
Computers also have a second type of memory, usually called RAM (Random Access Memory). RAM is much like ‘short term’ memory in humans. It is where we keep information which we are actively working on. RAM is designed to be much faster than a disk, but normally there is much less of it. A typical computer might have ~10 GB of RAM, while having ~1000 GB of disk space.
We typically use RAM as follows:
- Opening a file in Python creates a file object for accessing it; it does not automatically load the whole file into RAM.
- Reading the file brings data into the program. We can read all of it or process smaller pieces. The resulting strings and other objects remain available in memory while the program uses them.
- Writing sends data to a file, often through a buffer. Closing the file flushes Python’s pending output and releases the file resource. It does not erase variables containing data already read, and changing those variables does not automatically change the file.
Reading many large files into memory can put RAM under pressure. The operating system may move memory pages to storage (swap), which can slow the computer down. This is one possible cause of poor performance, not the only one.
The sum it all up, think of a information stored on disk as long-term, semi-permanent storage; while anything that the computer is currently working with is moved into active memory.
6.2 Files and Folders
Udacity · about 2 min. Understand how absolute paths locate a file from the root, while relative paths start from a current location.
When reading and writing data to the disk, the computer’s “operating system” (i.e. Windows, Mac, Ubuntu, etc.) presents us with a very familiar interface for dealing with stored data: files and folders.
One extremely frustrating feature of Windows is that the file extension is hidden by default, so the files appear as “my_resume” instead of “my_resume.docx”. Enabling this visibility is a very good idea. This tutorial shows the process for several different versions Windows.
- Data is stored in files.
- Common examples are are Word documents and images. We might have a Word document on our computer like
my_resume.docx, or a picture likefriends_at_pub.png. - The part after the last dot (
.) is called the file extension. - Extensions indicate the intended format and help applications and the operating system choose how to handle a file. Renaming an extension does not convert the contents: renaming an image to
.txtdoes not turn it into ordinary text. Some software also requires particular extensions.
- Common examples are are Word documents and images. We might have a Word document on our computer like
- Files are stored in folders.
- Common examples are your “downloads” or “documents” folder.
- Folders can contain many files
- Like real folders, folders can be stored inside other folders like
/pictures/2020/January/PartyInNYC.
- Finally, folders are stored on a disk.
- This is where the analogy to real world file systems breaks down because disks should be called “cabinets”.
- A drive is a physical storage device where data can be written. It may be internal or external to the computer.
- On Windows, mounted storage volumes commonly have drive letters, with
C:\usually containing the operating system. A physical drive can contain more than one volume. - On macOS, mounted volumes appear within one directory tree rooted at
/, rather than using drive letters.
- If we combine all of these together we get a path.
- On Windows the path looks like:
C:\users\jeff\photos\ufo_sightings\591.jpg
- And on Mac it looks like:
/Users/jeff/photos/bigfoot_sightings/431.jpg
These are absolute paths: they start at a drive’s root on Windows or / on macOS. A relative path is interpreted from the current working directory. For example, from C:\users\jeff, photos\ufo_sightings\591.jpg locates the same file as the absolute path above. Relative paths can also go upward: .. means the parent directory, so ../data/readings.csv means go up one level, then into data.
Note that Windows and Mac use different direction slashes. Recall the discussion about the use of escape characters when backslashes needed to be written (\\). This is particularly annoying on Windows since \ is used in the paths, while on Mac the / can be used without any escaping.
Below is a screenshot of a random folder deep within the Windows directory. Also shown is how title bar reports the absolute file path if you click it.
The point of storing files inside a hierarchical folder structure is for organization. Consider the file storage room in shown in Figure 6.5. If you are given a location (i.e. a path) in the form of aisle 8, section 4, shelf 4, box 11, page 10, line 55 you could find the exact sentence in a text file! The file system on a computer works exactly like this.
6.2.1 Finder/Explorer vs Command Line
Now that we understand how our computer stores our data in the form of files, we can appreciate what is happening when we browse our files using the Explorer in Windows (or Finder on Mac).
However, there is an alternative way to navigate our files: using the command line. Consider the following comparison:
A major milestone on the path to becoming a proficient programmer is learning to use the command prompt (sometimes known as the command line or terminal). Modern operating systems provide gorgeous and powerful graphical user interfaces (GUIs), but ultimately our button clicks and checkboxes get translated into commands to be run by the computer. The command prompt lets us call such commands directly, bypassing the GUI. There are 2 main scenarios where we may need to do this:
- As “power-users”, we often need to interact with the computer more directly than the GUI allows. The GUI hides many features and options since the vast majority of computer users do not need them.
- There are many essential utility applications which do not have a GUI so must be activated from the command prompt.
The following table illustrates an example of working from the command prompt to open a text editor, in both Windows and Mac.
| Windows | Mac |
|---|---|
Press Windows key to open Start Menu |
Press Command-Space to open Spotlight |
Type cmd and press enter |
Type terminal and press enter |
At the “prompt” (C:\) type notepad |
At the “prompt” type open -a TextEdit |
| When you press enter, the NotePad application will open up | When you press enter, the TextEdit app should open up |
| This is equivalent to opening the Start menu, typing “notepad” and clicking the application. | This is equivalent to opening Spotlight, typing “TextEdit” and opening the application. |
The number of commands that are available is enormous, and each one has different options. The following links provide “cheat sheets” for the most common and useful ones, to give a flavor of what is possible:
There are a few commands that are so common and useful that they are worth highlighting:
| Listing contents of current directory | In Windows the command is dir, while in Mac it is ls. |
| Changing current directory | Use cd on Windows and macOS. cd .. moves up one level; cd <folder> moves into the specified folder. Quote paths containing spaces, for example cd "Course Notes". |
6.3 Reading and Writing Text to a File
6.3.1 Writing to a File
Bro Code · about 3 min. Use with open(...) and write() to save text, and compare writing with appending.
Writing text to a file is one of the ways we can make our data “permanent”, otherwise all of our calculations are lost when we shutdown our computer.
Because this is such an important task, Python has a built-in function for working with a file: open(). The open() command does not “open” a file physically for us to look at, they way Word does when we double-click a file name. Instead Python “opens” the door to the file so that data can flow in and out.
The general syntax is as follows:
The usual way to ensure a file closes, even if an error occurs, is a with statement:
with open('data.txt', mode='w') as f:
f.write('Hello world')The indented block uses the open file; leaving it closes the file automatically. Common text modes are 'r' (read an existing file), 'w' (create or overwrite), and 'a' (append, creating the file if needed). Appending does not automatically insert a newline. See the Python file tutorial for more details.
If you create a file solely using a file name (i.e. no directory information), then the file will be created in Python’s “current working directory”. Luckily this is pretty easy to find:
- 1
-
The
osmodule has lots of functions for navigating your file system, as well as general information like the number of cores available, etc. - 2
-
Here
cwdstands for “current working directory”
This will return something like C:\Users\jeff\projects. If you navigate to this directory in your explorer/finder you will see your file (i.e. 'data.txt')
The result of writing “Hello world” to this file is shown in Figure 6.8 on the left:
Successive write() calls on the same open file continue at its current position. The following creates one long line as shown in Figure 6.8 (middle). Opening with 'w' first erases any previous contents; it does not append to an existing file from an earlier run.
fname = 'data.txt'
with open(file=fname, mode='w') as f:
f.write('Hello world')
f.write('Hello world')
f.write('Hello world')And finally, using our knowledge of escape characters from last chapter we can add a new line after each write to get the result in Figure 6.8 (right)
fname = 'data.txt'
with open(file=fname, mode='w') as f:
f.write('Hello world\n')
f.write('Hello world\n')
f.write('Hello world\n')Here is a good time to reveal how I know about all these hidden features buried under so many levels of abstraction:
I Google it!
I use a search term like “how to find the current time in python using standard library”. I usually look for the StackOverFlow links. Here is the page on StackOverflow. There are many answers, each proposing a different way to do it, complete with commentary by other coders and an upvote/downvote count to indicate how valuable the other users (like us!) found the answer.
6.3.2 Reading From a File
Bro Code · about 4 min. Read text with with open(...), let the file close automatically, and see how a missing file can be handled.
Reading data from a file not only let’s us reload data we may have written to a file, but it is also common to store tabulated data like constants and fitting parameters in files.
Let’s start with something simple to see how it works:
- 1
- First we will open a new file and write “Hello world” in it to ensure the file is present.
- 2
-
Here we open the file in “read” mode (
'r'). - 3
-
read()reads from the current position to the end. Here the file has just been opened, so it reads all the text.contentsremains available after the file is closed. A secondread()before closing would return''because the position is already at the end.
Result: Hello world
6.4 Installing External Packages
Bro Code · about 4 min. Install, list, and update packages with pip. For this course, use the python -m pip form shown below so pip runs with your intended Python interpreter.
We have already dabble in this briefly when installing streamlit to run the checker apps, but let’s take a closer look.
We have already seen that Python includes many additional packages as part of the “standard library”. These provide functionality that is often important, but not necessary for everyone. The programmer can therefore import the extra functionality when needed.
Although Python’s standard library is considered very good (compared to most languages), it cannot possibly consider everything. For this reason we can install “external packages” from a variety of sources. The most common source is The Python Package Index or PyPI.
Package installation is one reason to learn the command line. Run python -m pip install <package-name> with the Python interpreter used by your project. Replace <package-name> with the package name; the angle brackets are placeholders.
For our purposes, we can avoid complications by using the anaconda_prompt via the Anaconda Navigator.
The conda prompt configures the shell to use a conda environment; it does not provide a special kind of pip. Activate your intended environment (for example, conda activate ne111 if you have created an environment named ne111). Configure Spyder or your notebook kernel to use that same environment. Check the interpreter and its installed packages with:
python -c "import sys; print(sys.executable)"
python -m pip list
The first command displays the Python executable being used. The second runs that interpreter’s pip module and lists packages in its environment. If an installed package cannot be imported in the IDE, compare sys.executable there with the command-line result.
Now that we have the ability to to install and use more complicated packages, we can revisit some tasks and do them differently.
6.5 Assignment 5
Submit one Jupyter notebook named A5.ipynb. Use one code cell for each question. The first non-blank line in each cell must be its indicated tag, such as # A5Q1. Write code directly in the cells and assign each result to answer. For questions that write or append to a file, assign None to answer after completing the file operation. Close files before the cell ends.
The checker supplies fresh input values each time it runs a cell. To test in Jupyter, you may place your own example input assignments at the start of the cell, after the tag. The checker replaces these initial assignments with its own values. Each question must work independently of the other question cells. Put shared imports in a cell whose first non-blank line is # setup, or import libraries in the question cell. Do not use notebook magics or shell commands.
Install and run the checker using the instructions in Appendix E, replacing A1 with A5. Save your notebook, then run python -m ne111_checker A5 on Windows or python3 -m ne111_checker A5 on macOS from any folder. Click Browse… in the checker to select your saved A5.ipynb. Save changes before running a question again; the checker rereads the selected file automatically.
For your own tests in Jupyter, download these files into the notebook’s working directory (right-click and choose Save link as if needed):
The checker creates its own copies of the input files in a temporary working directory for each test. Files written by the checker stay in that temporary directory; files written when you run a cell in Jupyter use Jupyter’s current working directory. Use the supplied filenames rather than absolute paths.
The checker provides filename, the name of an existing text file in the current working directory. Open and read the file, then assign the number of lines to answer. Count blank lines too; a final line without a trailing newline still counts as a line.
Cell tag: # A5Q1
For example, a file containing "this\nis\na\n\n\nfile" has 6 lines.
The checker provides filename, the name of an existing text file in the current working directory. Open and read the file, then assign its number of words to answer. Words are separated by whitespace; spaces, tabs (\t), and newlines (\n) do not count as words.
Cell tag: # A5Q2
For example, a file containing "this\nis\na\n\n\nfile" has 4 words.
The checker provides filename, a string value, and a non-negative integer repetitions. Write value to the file repetitions times, with a newline after each copy. Replace any existing contents and store the file in the current working directory. You may assume value contains no newline characters. Assign None to answer after writing the file.
Cell tag: # A5Q3
For example, value = "line" and repetitions = 3 should produce "line\nline\nline\n".
The checker provides filename and a dictionary data containing columnar data. Each key is a column heading and each value is a list of column values; all lists have the same length. Write the data to a CSV file in the current working directory, using the keys as column headings and omitting any row index. If filename does not end with .csv, add that extension. Assign None to answer after writing the file. You may use pandas.
Cell tag: # A5Q4
For example, filename = "data2" or filename = "data2.csv" should write data2.csv. For data = {"a": [9, 8, 7], "b": [6, 5, 4]}, its contents are:
a,b
9,6
8,5
7,4
The checker provides filename, the name of an existing CSV file in the current working directory. If the supplied name does not end with .csv, add that extension before opening the file. Read the data and assign a dictionary to answer, with each column heading as a key and its column values as a list. Keep numeric values as numbers. You may use pandas.
Cell tag: # A5Q5
For example, filename = "data" or filename = "data.csv" refers to data.csv. If the file contains "x,y\n1,4\n2,5\n3,6", the expected answer is {"x": [1, 2, 3], "y": [4, 5, 6]}.
The checker provides filename, the name of an existing text file in the current working directory, and a string value with no newline characters. Append value on a new line, preserving all existing contents. The existing file may have no trailing newline. Assign None to answer after appending.
Cell tag: # A5Q6
For example, appending "new line" to a file containing "first line" should leave "first line\nnew line" (a final trailing newline is also allowed).











