1. Operating System (OS) Commands in the Notebook

Files are usually organized in folders (also known as directories). In the Jupyter notebook, we can directly use certain OS (operating system) commands to figure out information about files and folders.

  • pwd : print working directory
  • cd dirName : change the working directory to dirName
    • cd .. : change the working directory to the parent of the current working directory. (In general, .. means "parent of the current directory" and . means "the current directory".)
  • ls : list the contents of working directory
    • ls dirName: list the contents of directory dirName
    • the -a flag to ls includes hidden files (begin with a dot)
    • the -l flag to ls puts each file on a line with extra information (size, timestamp, etc)
    • the -a and -l flags can be combined as -al

Let's try them below to see the results.

In [1]:
pwd
Out[1]:
'/Users/emustafa/Documents/CS111-Fall21/cs111-site/content/lectures/lec_fileTrees/files/lec_fileTrees_solns'
In [2]:
ls
books/                     lec_fileTrees_solns.ipynb
books2/                    pics/
lec_fileTrees_solns.html   testdir/
In [3]:
cd testdir
/Users/emustafa/Documents/CS111-Fall21/cs111-site/content/lectures/lec_fileTrees/files/lec_fileTrees_solns/testdir
In [4]:
pwd
Out[4]:
'/Users/emustafa/Documents/CS111-Fall21/cs111-site/content/lectures/lec_fileTrees/files/lec_fileTrees_solns/testdir'
In [5]:
ls
hyp.py      pset/       pubs.json   remember/   tracks.csv
In [6]:
ls -a
./          .numbers    pset/       remember/
../         hyp.py      pubs.json   tracks.csv
In [7]:
ls -al
total 272
drwxr-xr-x   8 emustafa  staff     256 Aug 13 05:41 ./
drwxr-xr-x  11 emustafa  staff     352 Nov  2 15:16 ../
-rw-r--r--   1 emustafa  staff      21 Aug 13 05:41 .numbers
-rw-r--r--   1 emustafa  staff      94 Aug 13 05:41 hyp.py
drwxr-xr-x   4 emustafa  staff     128 Aug 13 05:41 pset/
-rw-r--r--   1 emustafa  staff  107062 Aug 13 05:41 pubs.json
drwxr-xr-x   5 emustafa  staff     160 Aug 13 05:41 remember/
-rw-r--r--   1 emustafa  staff   18778 Aug 13 05:41 tracks.csv
In [8]:
cd ..
/Users/emustafa/Documents/CS111-Fall21/cs111-site/content/lectures/lec_fileTrees/files/lec_fileTrees_solns

IMPORTANT: All these command lines can be used in the Terminal application in a Mac computer to navigate folders in the computer. Alternatively, they are performed via point-and-click operations in the Finder application. Windows uses similar (but slightly different) commands from the Command Prompt.

2. File System Operations

We will experiment with a file tree that looks like this:

A file tree is defined as:

  • a file (a leaf of the tree). In the above tree, files are represented by the document icon.

  • a directory (a.k.a. folder, an intermediate node of the tree) containing zero or more file trees. In the above tree, directories are represented by the folder icon.

The top node of the tree (in this case, the folder named lec_fileTrees) is called the root of the tree.

Tree-shaped structures consisting of nodes that branch out to subtrees that terminate in leaves are common in computer science. We focus on file trees in this lecture because everyone is familiar with them and it is important to understand their structure when working with data and your own computers.

We can also use a text-based representation to display file trees as well. Here is one such example below:

.
|-- .data
|-- testdir
|   |-- remember
|   |   |-- persistent.py
|   |   |-- memories.txt
|   |   |-- ephemeral.py
|   |-- hyp.py
|   |-- pubs.json
|   |-- pset
|   |   |-- scene
|   |   |   |-- cs1graphics.py
|   |   |-- shrub
|   |   |   |-- images
|   |   |   |   |-- shrub2.png
|   |   |   |   |-- shrub1.png
|   |   |   |-- shrub.py
|   |-- .numbers
|   |-- tracks.csv
|-- books
|   |-- jane_austen
|   |   |-- Pride_and_Prejudice.txt
|   |   |-- Mansfield_Park.txt
|   |-- charlotte_perkins_gilman
|   |   |-- The_Yellow_Wallpaper.txt
|   |   |-- Women_and_Economics.txt
|   |-- oscar_wilde
|   |   |-- The_Importance_of_Being_Earnest.txt
|   |   |-- The_Picture_of_Dorian_Gray.txt
|-- pics
|   |-- fileListingWithHiddenFiles.png
|   |-- fileTreeRootedAtTestdir.png
|   |-- fileTree.png
|   |-- fileListingWithoutHiddenFiles.png
|-- books2
|   |-- zora_neale_hurston
|   |   |-- Three_Plays.txt
|   |   |-- Poker!.txt
|   |-- charlotte_bronte
|   |   |-- Jane_Eyre.txt
|   |   |-- The_Professor.txt
|   |-- lewis_carroll
|   |   |-- Alice_in_Wonderland.txt
|   |   |-- Symbolic_Logic.txt
|   |   |-- Through_the_Looking-Glass.txt
|-- lec_fileTrees_solns.ipynb

Via the os module, Python provides a way to manipulate the directories and files in a file system. To use these features, we first need to import the os module:

In [9]:
import os

(a) Get working directory: os.getcwd

The os.getcwd function returns the current working directory as a string.

In [10]:
os.getcwd()
Out[10]:
'/Users/emustafa/Documents/CS111-Fall21/cs111-site/content/lectures/lec_fileTrees/files/lec_fileTrees_solns'

(b) List directory: os.listdir

The os.listdir function returns a list of all files/directories in the argument directory.

In [11]:
os.listdir(os.getcwd())
Out[11]:
['lec_fileTrees_solns.ipynb',
 'books2',
 '.DS_Store',
 'pics',
 'books',
 'testdir',
 '.data',
 '.ipynb_checkpoints',
 'lec_fileTrees_solns.html']

So-called "dot files" whose names begin with the '.' character are special system files that are often hidden by the operating system when displaying files. We will tend to ignore them. Note that "dot files" do not include . (the current directory) or .. (the parent directory).

Depending on the settings for your computer's file browser (e.g., Finder on a Mac), you might or might not see dot files explicitly listed in the file browser. For example, here's a version of a Mac Finder window where hidden files are shown:

And here's a version of a Mac Finder window where dot files are not shown. Note that by default newer versions of Finder will not show .DS_store files:

Let's see more examples of os.listdir:

In [12]:
os.listdir('testdir')
Out[12]:
['tracks.csv', '.numbers', 'pset', 'pubs.json', 'hyp.py', 'remember']
In [13]:
os.listdir('testdir/remember')
Out[13]:
['ephemeral.py', 'memories.txt', 'persistent.py']
In [14]:
os.listdir('testdir/pset')
Out[14]:
['shrub', 'scene']
In [15]:
os.listdir('testdir/pset/scene')
Out[15]:
['cs1graphics.py']
In [16]:
os.listdir('testdir/pset/shrub')
Out[16]:
['shrub.py', 'images']

YOUR TURN: Below, write a command that lists the content for the subfolder "images".
The expected result is ['shrub1.png', 'shrub2.png'].

In [17]:
# Your code here
os.listdir('testdir/pset/shrub/images')
Out[17]:
['shrub1.png', 'shrub2.png']

What happens if the os.listdir is given the name of a nondirectory file or a nonexistent file?

In [18]:
os.listdir('testdir/hyp.py')
---------------------------------------------------------------------------
NotADirectoryError                        Traceback (most recent call last)
<ipython-input-18-29525f482b7b> in <module>
----> 1 os.listdir('testdir/hyp.py')

NotADirectoryError: [Errno 20] Not a directory: 'testdir/hyp.py'
In [19]:
os.listdir('remember') # Not a subdirectory of the connected directory
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-19-60b49785fae3> in <module>
----> 1 os.listdir('remember') # Not a subdirectory of the connected directory

FileNotFoundError: [Errno 2] No such file or directory: 'remember'

(c) Does this path exist?

The os.path.exists function determines whether the given name denotes a file/directory in the filesystem.

In [20]:
os.path.exists('testdir/remember/memories.txt')
Out[20]:
True
In [21]:
os.path.exists('testdir/remember')
Out[21]:
True
In [22]:
os.path.exists('catPlaysPiano.jpg')
Out[22]:
False
In [23]:
os.path.exists('remember')
Out[23]:
False

Note that the search for a file/directory begins in the working directory, which in the above examples is the lec_fileTrees directory. This is why os.path.exists('testdir/remember') is True but os.path.exists('remember') is False.

YOUR TURN: How would you check that the file cs1graphics.py is in the sample file tree?

In [24]:
# Your code here
os.path.exists('testdir/pset/scene/cs1graphics.py')
Out[24]:
True

(d) Determine file or directory status

The os.path.isfile and os.path.isdir functions determine whether the given name is a file or directory, respectively. They both return false for a nonexistent file/directory name.

In [25]:
os.path.isfile('testdir/remember/memories.txt')
Out[25]:
True
In [26]:
os.path.isdir('testdir/remember/memories.txt')
Out[26]:
False
In [27]:
os.path.isfile('testdir/remember/')
Out[27]:
False
In [28]:
os.path.isdir('testdir/remember/')
Out[28]:
True
In [29]:
os.path.isfile('remember')
Out[29]:
False
In [30]:
os.path.isdir('remember')
Out[30]:
False

YOUR TURN: Verify that shrub1.png is a file, using the correct path.

In [31]:
# Your code here
os.path.isfile('testdir/pset/shrub/images/shrub1.png')
Out[31]:
True

YOUR TURN: Verify that scene is a directory, using the correct path.

In [32]:
# Your code here
os.path.isdir('testdir/pset/scene')
Out[32]:
True

(e) Creating a path with os.path.join

We can use os.path.join to join to strings that contain parts of the path. We often need to do this together with os.listdir, which only shows the names of the contained files and directories without their relative paths.

In [33]:
root = 'testdir'
for name in os.listdir(root):
    print(name)
tracks.csv
.numbers
pset
pubs.json
hyp.py
remember

But, joining the root folder with the file name gives the entire relative path for a file/folder:

In [34]:
root = 'testdir'
for name in os.listdir(root):
    print(os.path.join(root, name))
testdir/tracks.csv
testdir/.numbers
testdir/pset
testdir/pubs.json
testdir/hyp.py
testdir/remember

We could instead use string concatenation via + to combine path elements, but os.path.join is more convenient for handling the slashes that separate path components.

In [35]:
os.path.join('testdir/', 'remember/', 'memories.txt')
Out[35]:
'testdir/remember/memories.txt'
In [36]:
os.path.join('testdir', 'remember', 'memories.txt')
Out[36]:
'testdir/remember/memories.txt'
In [37]:
'testdir' + '/' + 'remember' + '/' + 'memories.txt'
Out[37]:
'testdir/remember/memories.txt'

YOUR TURN: Modify the above for loop to print out the relative paths of only the directories in testdir. You'll need to use one of the functions we learned in this section, in addition to os.path.join:

In [38]:
# Your code here
root = 'testdir'
for name in os.listdir(root):
    pathName = os.path.join(root, name)
    if os.path.isdir(pathName):
        print(pathName)
testdir/pset
testdir/remember

(f) Getting the last component of path with os.path.basename

os.path.basename returns the last component in a file path.

In [39]:
os.path.basename('testdir/remember/memories.txt')
Out[39]:
'memories.txt'
In [40]:
os.path.basename('testdir/remember')
Out[40]:
'remember'
In [41]:
os.path.basename('testdir/remember/')
Out[41]:
''

(g) Getting the size of files and folder with os.path.getsize

A file has a size measured in bytes. For a folder, the size only refers to some bookkeeping information; it does not refer to the total size of the files in the folder!

In [42]:
os.path.getsize("testdir/remember/ephemeral.py")
Out[42]:
379
In [43]:
os.path.getsize("testdir/remember/memories.txt")
Out[43]:
80
In [44]:
os.path.getsize("testdir/remember/persistent.py")
Out[44]:
1634
In [45]:
os.path.getsize("testdir/remember")
Out[45]:
160

Note that 160 is less than (379 + 80 + 1634); it is unrelated to the sizes of the files in the remember directory!

In [46]:
os.path.getsize("testdir/tracks.csv")
Out[46]:
18778
In [47]:
os.path.getsize("testdir")
Out[47]:
256

3. Exercise 1: Relative Paths

Write a for loop that will print (1) the relative path name of each element in the testdir folder along with (2) its size. The solution should look like this (note that your order may be different):

testdir/.DS_Store 6148 # This might or might not appear, depending on your operating system. 
testdir/.numbers 21
testdir/hyp.py 94
testdir/pset 170
testdir/pubs.json 107062
testdir/remember 170
testdir/tracks.csv 18778

Note: this is trickier than it might first appear. Mastering this pattern is essential for writing functions that manipulate file trees (see the next section).

In [ ]:
# Your code here
folder = 'testdir'
for name in os.listdir(folder):
    wholeName = os.path.join(folder, name)
    print(wholeName, os.path.getsize(wholeName))

4. Exercise 2: printSubFolders

Write a function that given some path to a folder, prints all subfolders contained in that folder.

In [48]:
# Your code here
def printSubFolders(folderPath):
    for f in os.listdir(folderPath):
        if os.path.isdir(os.path.join(folderPath, f)):
            print(f)
In [49]:
printSubFolders("testdir")          # should print pset and remember
pset
remember
In [50]:
printSubFolders("testdir/remember") # should print nothing
In [51]:
printSubFolders("testdir/pset")     # should print shrub and scene
shrub
scene

5. Reading from File Trees

Understanding file trees is essential when working with large data because data tends to be split across many files and folders. Below is a file tree of some data we will work with in the coming examples. The folder books contains folders of authors. Each author folder contains complete books found from Project Gutenberg. We will use the next series of examples to analyze some properties of all the books. To do so we will need to read multiple files spread across a file tree. Below is a file tree of the books folder.

books
|-- jane_austen
|   |-- Pride_and_Prejudice.txt
|   |-- Mansfield_Park.txt
|-- charlotte_perkins_gilman
|   |-- The_Yellow_Wallpaper.txt
|   |-- Women_and_Economics.txt
|-- oscar_wilde
|   |-- The_Importance_of_Being_Earnest.txt
|   |-- The_Picture_of_Dorian_Gray.txt

There is also another folder containing books called books2. It follows the same structure in that subfolders of books2 are authors that contain books.

5.1 Understanding books

The books folder contains three subfolders as shown below using os.listdir. Those subfolders are author names.

In [52]:
os.listdir("books")
Out[52]:
['oscar_wilde', 'charlotte_perkins_gilman', 'jane_austen']

Each author folder contains files for each book of that author.

In [53]:
os.listdir("books/jane_austen")
Out[53]:
['Mansfield_Park.txt', 'Pride_and_Prejudice.txt']

Let's revisit how to read from a file. To read a file, we use a with block. Remember the with block will automatically close the file when we are done. Below is a function that takes a filepath and opens the file at that file path. We can use open with any valid file path as long as the file path is a file. If not, we will raise an error.

In [54]:
def printBookLines(bookPath, numLines):
    with open(bookPath, "r") as book:
        for _ in range(numLines):
            print(book.readline())
In [55]:
printBookLines("books/jane_austen/Pride_and_Prejudice.txt", 30)
´╗┐The Project Gutenberg eBook of Pride and Prejudice, by Jane Austen



This eBook is for the use of anyone anywhere in the United States and

most other parts of the world at no cost and with almost no restrictions

whatsoever. You may copy it, give it away or re-use it under the terms

of the Project Gutenberg License included with this eBook or online at

www.gutenberg.org. If you are not located in the United States, you

will have to check the laws of the country where you are located before

using this eBook.



Title: Pride and Prejudice



Author: Jane Austen



Release Date: June, 1998 [eBook #1342]

[Most recently updated: February 10, 2021]



Language: English



Character set encoding: UTF-8



Produced by: Anonymous Volunteers and David Widger



*** START OF THE PROJECT GUTENBERG EBOOK PRIDE AND PREJUDICE ***



THERE IS AN ILLUSTRATED EDITION OF THIS TITLE WHICH MAY VIEWED AT EBOOK

[# 42671 ]



cover



In [56]:
printBookLines("books", 10) # error because `books` is a folder and not a file
---------------------------------------------------------------------------
IsADirectoryError                         Traceback (most recent call last)
<ipython-input-56-149162d92170> in <module>
----> 1 printBookLines("books", 10) # error because `books` is a folder and not a file

<ipython-input-54-4626d9cc73f2> in printBookLines(bookPath, numLines)
      1 def printBookLines(bookPath, numLines):
----> 2     with open(bookPath, "r") as book:
      3         for _ in range(numLines):
      4             print(book.readline())

IsADirectoryError: [Errno 21] Is a directory: 'books'

5.2 Getting the file paths of subfiles and folders

Below is a function that returns a list of all the paths to each book. This will be a critical helper function in the next series of exercises. How does it work? It requires a nested loop with the outer loop cycling through all the author folders and the inner loop going through each book of the author folders. Notice that we filter out all files and hidden files/folders. This removes the pesky .DS_store for example that is common in MacOS file systems.

In [57]:
def getBookPaths(rootFolder):
    paths = []
    for author in os.listdir(rootFolder):
        authorFolderPath = os.path.join(rootFolder, author)
        
        # filter out hidden files and non-directories like .DS_Store
        if os.path.isdir(authorFolderPath) and author[0] != ".": 
            for book in os.listdir(authorFolderPath):
                if not book.startswith('.'):     # filter out hidden files
                    bookPath = os.path.join(authorFolderPath, book)
                    paths.append(bookPath)
    return paths                
In [58]:
getBookPaths("books")
Out[58]:
['books/oscar_wilde/The_Picture_of_Dorian_Gray.txt',
 'books/oscar_wilde/The_Importance_of_Being_Earnest.txt',
 'books/charlotte_perkins_gilman/Women_and_Economics.txt',
 'books/charlotte_perkins_gilman/The_Yellow_Wallpaper.txt',
 'books/jane_austen/Mansfield_Park.txt',
 'books/jane_austen/Pride_and_Prejudice.txt']
In [59]:
getBookPaths("books2")
Out[59]:
['books2/lewis_carroll/Through_the_Looking-Glass.txt',
 'books2/lewis_carroll/Symbolic_Logic.txt',
 'books2/lewis_carroll/Alice_in_Wonderland.txt',
 'books2/charlotte_bronte/The_Professor.txt',
 'books2/charlotte_bronte/Jane_Eyre.txt',
 'books2/zora_neale_hurston/Poker!.txt',
 'books2/zora_neale_hurston/Three_Plays.txt']

5.3 largestBookSize

Using the function we wrote above, we can write a function called largestBookSize that returns the largest book in bytes from the books folder. Here we can go through all the paths and use os.path.getsize to get the size of each book.

In [60]:
def largestBookSize(rootFolder):
    largestBook = ("", 0) # a tuple to store a file title and its size
    paths = getBookPaths(rootFolder)
    for bookPath in paths:
        bookSize = os.path.getsize(bookPath)
        book = os.path.basename(bookPath) # the last part of the path is the book file name
        if bookSize > largestBook[1]:
            largestBook = book, bookSize
    return largestBook            
In [61]:
largestBookSize("books")
Out[61]:
('Mansfield_Park.txt', 928708)
In [62]:
largestBookSize("books2")
Out[62]:
('Jane_Eyre.txt', 1084733)

Exercise 3: totalLines

Below write a function that gets the total number of lines of all the books from a folder structured like the books folder (i.e., it should work for both books and books2). Your function should return a list of tuples where each tuple should contain the file name of the book and the number of lines. Below is the sample output of the function when called with books. Your function should take one argument: the root folder of a book directory. Resist the urge to use the len function would require you to read in all the lines of the book at once. This requires a lot of memory. Instead loop over each line of the book and increment a counter to get the total number of lines.

[('The_Picture_of_Dorian_Gray.txt', 8908),
 ('The_Importance_of_Being_Earnest.txt', 4269),
 ('Women_and_Economics.txt', 10132),
 ('The_Yellow_Wallpaper.txt', 1225),
 ('Mansfield_Park.txt', 16054),
 ('Pride_and_Prejudice.txt', 14580)]

Note: You should use getBookPaths to get the list of file paths for all books.

In [63]:
# Your code here

def totalLines(rootFolder):
    bookLines = []
    paths = getBookPaths(rootFolder)
    for bookPath in paths:
        bookName = os.path.basename(bookPath)
        with open(bookPath) as book:
            lineCount = 0
            for line in book:
                lineCount +=1
            bookLines.append((bookName, lineCount))
    return bookLines
In [64]:
totalLines("books")
Out[64]:
[('The_Picture_of_Dorian_Gray.txt', 8908),
 ('The_Importance_of_Being_Earnest.txt', 4269),
 ('Women_and_Economics.txt', 10132),
 ('The_Yellow_Wallpaper.txt', 1225),
 ('Mansfield_Park.txt', 16054),
 ('Pride_and_Prejudice.txt', 14580)]
In [65]:
totalLines("books2")
Out[65]:
[('Through_the_Looking-Glass.txt', 4448),
 ('Symbolic_Logic.txt', 14214),
 ('Alice_in_Wonderland.txt', 3761),
 ('The_Professor.txt', 9797),
 ('Jane_Eyre.txt', 21386),
 ('Poker!.txt', 604),
 ('Three_Plays.txt', 1433)]

Exercise 4: totalSentences

Write a function called totalSentences that takes a path to a book folder like books and returns a list of tuples where each tuple contains the name of the book and the number of sentences in the book. How do we determine the number of sentences in a book? One simple, though potentially inaccurate way, is to simply count the number of periods in the book. This may not be the most accurate because the period could be used in formatting at the beginning and end of the book. Other books can use punctuation (or the lack thereof) in interesting ways like Faulkner's "The Sound and the Fury".

We will take the simple approach and simply count the number of periods. You can use the string method .count which counts the number of instances of a substring in some other string. For example, "AbraAbra".count("Abra") evaluates to 2.

Here is the output of totalSentences("books"):

[('The_Picture_of_Dorian_Gray.txt', 6049),
 ('The_Importance_of_Being_Earnest.txt', 3119),
 ('Women_and_Economics.txt', 4390),
 ('The_Yellow_Wallpaper.txt', 516),
 ('Mansfield_Park.txt', 7118),
 ('Pride_and_Prejudice.txt', 6402)]
In [66]:
# Your code here

def totalSentences(rootFolder):
    bookSentCount = []
    paths = getBookPaths(rootFolder)
    for bookPath in paths:
        bookName = os.path.basename(bookPath)
        with open(bookPath) as book:
            count = 0
            for line in book:
                count += line.count(".")
            bookSentCount.append((bookName, count))
    return bookSentCount
In [67]:
totalSentences("books")
Out[67]:
[('The_Picture_of_Dorian_Gray.txt', 6049),
 ('The_Importance_of_Being_Earnest.txt', 3119),
 ('Women_and_Economics.txt', 4390),
 ('The_Yellow_Wallpaper.txt', 516),
 ('Mansfield_Park.txt', 7118),
 ('Pride_and_Prejudice.txt', 6402)]
In [68]:
totalSentences("books2")
Out[68]:
[('Through_the_Looking-Glass.txt', 1692),
 ('Symbolic_Logic.txt', 6538),
 ('Alice_in_Wonderland.txt', 1222),
 ('The_Professor.txt', 3219),
 ('Jane_Eyre.txt', 8627),
 ('Poker!.txt', 270),
 ('Three_Plays.txt', 581)]

Exercise 5: wordOccurrences

Write a function called wordOccurrences that counts the number of times a word appears in each book. wordOccurrences should take a path to folder structured like books and a word to look for. Counting the number of occurrences of a word is not an easy task. There are many factors to consider:

  • Should case matter? Maybe not for most words but probably for proper nouns.
  • Should plurality matter for nouns? Is "water" the same as "waters"?
  • How do we define the surrounding criteria for a word? For example, if we are searching for occurrences of "he", we need to be careful to not count words like "the". An easy heuristic is to mandate that a word have a space on either side. This would ensure we do not count words like "the" for "he". However, what if the word is the last word of a sentence? Then it would have punctuation and not spaces but should count as a word.

To make our lives simpler, we will define the occurrence of a word as having a space on either side and ignore case. Of course, this will not be a perfect word counter. As a challenge see if you can define better criteria and implement it in code for a more robust word counter.

Below is the sample output from wordOccurrences("books", "she"):

[('The_Picture_of_Dorian_Gray.txt', 312),
 ('The_Importance_of_Being_Earnest.txt', 40),
 ('Women_and_Economics.txt', 239),
 ('The_Yellow_Wallpaper.txt', 21),
 ('Mansfield_Park.txt', 1671),
 ('Pride_and_Prejudice.txt', 1368)]
In [70]:
# Your code here

def wordOccurrences(rootFolder, word):
    wordCount = []
    testWord = " " + word.lower() + " " # word has to have spaces around it; also ignore case
    paths = getBookPaths(rootFolder)
    for bookPath in paths:
        bookName = os.path.basename(bookPath)
        with open(bookPath) as book:
            count = 0
            for line in book:
                if testWord in line.lower():
                    count += 1
            wordCount.append((bookName, count))
    return wordCount
In [71]:
wordOccurrences("books", "she")
Out[71]:
[('The_Picture_of_Dorian_Gray.txt', 312),
 ('The_Importance_of_Being_Earnest.txt', 40),
 ('Women_and_Economics.txt', 239),
 ('The_Yellow_Wallpaper.txt', 21),
 ('Mansfield_Park.txt', 1671),
 ('Pride_and_Prejudice.txt', 1368)]
In [72]:
wordOccurrences("books", "he")
Out[72]:
[('The_Picture_of_Dorian_Gray.txt', 1140),
 ('The_Importance_of_Being_Earnest.txt', 75),
 ('Women_and_Economics.txt', 195),
 ('The_Yellow_Wallpaper.txt', 42),
 ('Mansfield_Park.txt', 1171),
 ('Pride_and_Prejudice.txt', 1073)]
In [73]:
wordOccurrences("books", "water")
Out[73]:
[('The_Picture_of_Dorian_Gray.txt', 2),
 ('The_Importance_of_Being_Earnest.txt', 2),
 ('Women_and_Economics.txt', 3),
 ('The_Yellow_Wallpaper.txt', 0),
 ('Mansfield_Park.txt', 4),
 ('Pride_and_Prejudice.txt', 0)]

Super Challenge: Create a File Tree

Write a function called fileTree that prints out a text-based version of a file tree. For example, here is the output of the file tree on the books folder.

books
|-- jane_austen
|   |-- Pride_and_Prejudice.txt
|   |-- Mansfield_Park.txt
|-- charlotte_perkins_gilman
|   |-- The_Yellow_Wallpaper.txt
|   |-- Women_and_Economics.txt
|-- oscar_wilde
|   |-- The_Importance_of_Being_Earnest.txt
|   |-- The_Picture_of_Dorian_Gray.txt

This is a real challenge and unlike any programming paradigm you have seen so far though it does not require any new tools or syntax. We would not expect to give you any question like this on an exam or even problem set without a lot of structure/scaffolding. But challenges are good!

The trick is to use a list that keeps track of all the file paths and grows as new folders are discovered. The list should contain tuples of file paths and "levels". Notice how the file tree becomes indented as it is nested. You will need some way to keep track of that information.

In [74]:
# Your code here

def fileTree(rootFolder):
    paths = [(rootFolder, 0)]
    levelStr = "|   "
    fileStr = "|-- "
    
    while len(paths) > 0:
        path, level = paths.pop()
        name = os.path.basename(path)
        if level == 0:
            print(name)
        else:
            print((level - 1) * levelStr + fileStr + name)
        if os.path.isdir(path):
            for sub in os.listdir(path):
                paths.append((os.path.join(path, sub), level + 1))
            
In [75]:
fileTree("books")
books
|-- jane_austen
|   |-- Pride_and_Prejudice.txt
|   |-- Mansfield_Park.txt
|-- charlotte_perkins_gilman
|   |-- The_Yellow_Wallpaper.txt
|   |-- Women_and_Economics.txt
|-- oscar_wilde
|   |-- The_Importance_of_Being_Earnest.txt
|   |-- The_Picture_of_Dorian_Gray.txt
In [76]:
fileTree("books2")
books2
|-- zora_neale_hurston
|   |-- Three_Plays.txt
|   |-- Poker!.txt
|-- charlotte_bronte
|   |-- Jane_Eyre.txt
|   |-- The_Professor.txt
|-- lewis_carroll
|   |-- Alice_in_Wonderland.txt
|   |-- Symbolic_Logic.txt
|   |-- Through_the_Looking-Glass.txt
In [77]:
fileTree(".")
.
|-- lec_fileTrees_solns.html
|-- .ipynb_checkpoints
|   |-- lec_fileTrees_solns-checkpoint.ipynb
|-- .data
|-- testdir
|   |-- remember
|   |   |-- persistent.py
|   |   |-- memories.txt
|   |   |-- ephemeral.py
|   |-- hyp.py
|   |-- pubs.json
|   |-- pset
|   |   |-- scene
|   |   |   |-- cs1graphics.py
|   |   |-- shrub
|   |   |   |-- images
|   |   |   |   |-- shrub2.png
|   |   |   |   |-- shrub1.png
|   |   |   |-- shrub.py
|   |-- .numbers
|   |-- tracks.csv
|-- books
|   |-- jane_austen
|   |   |-- Pride_and_Prejudice.txt
|   |   |-- Mansfield_Park.txt
|   |-- charlotte_perkins_gilman
|   |   |-- The_Yellow_Wallpaper.txt
|   |   |-- Women_and_Economics.txt
|   |-- oscar_wilde
|   |   |-- The_Importance_of_Being_Earnest.txt
|   |   |-- The_Picture_of_Dorian_Gray.txt
|-- test_lecture.py
|-- pics
|   |-- fileListingWithHiddenFiles.png
|   |-- fileTreeRootedAtTestdir.png
|   |-- fileTree.png
|   |-- fileListingWithoutHiddenFiles.png
|-- .DS_Store
|-- books2
|   |-- zora_neale_hurston
|   |   |-- Three_Plays.txt
|   |   |-- Poker!.txt
|   |-- charlotte_bronte
|   |   |-- Jane_Eyre.txt
|   |   |-- The_Professor.txt
|   |-- lewis_carroll
|   |   |-- Alice_in_Wonderland.txt
|   |   |-- Symbolic_Logic.txt
|   |   |-- Through_the_Looking-Glass.txt
|-- lec_fileTrees_solns.ipynb

That's all folks!