@extends('template') @section('title') Lab 13: File traversal treasure hunt @stop @section('content') # Lab 13: File traversal treasure hunt ## Setup In `lab13/random` there's a bunch of random folders with cryptic, one-letter names, nested several levels deep.
As you can see, some of the folders contain a text file. Most of these text files contain the string `not in here`:
**Some** of these text files contains the string `treasure!`: Your job is to write a function that “finds the treasure”; i.e. the file(s) that contain the string `treasure!`. ## Task 1. In `lab13/treasureHunt.py` you will complete the function `findTheTreasure`. __Before starting, read through all the instructions and hints below.__ Your `findTheTreasure` function should recursively traverse all the folders/files in the given directory and when it encounters a file that contains the string `treasure!` it should **print** something like the following: If there was only 1 “treasure”: ```xml Found treasure in random/v/x/e/t/w.txt ``` If there were multiple “treasures”: ```xml Found treasure in random/v/x/e/t/w.txt Found treasure in random/b/f/e/n/e.txt Found treasure in random/g/c/x/w/r.txt ``` (These are just examples, they are not the actual answer(s) you're looking for) ### Hint 1 In [Lecture 23, Slide 15 *File Tree Traversal* (click to see lec notes)](http://cs111.wellesley.edu/content/lectures/lec_fileTrees/files/lec_fileTrees.pdf), you saw the function `printFileTreeBetter`: ```py def printFileTreeBetter(root): if os.path.isfile(root): print(root) elif os.path.isdir(root): print(root) for fileOrDir in os.listdir(root): printFileTreeBetter(os.path.join(root, fileOrDir)) ``` This function can act as a starting point for this task as it shows how to recursively iterate through a directory. ### Hint 2 When your function encounters a file, it needs to open it and see if it contains the treasure. Refer to [Lecture Files, Slides 6-8](http://cs111.wellesley.edu/content/lectures/lec_files/files/lec_files.pdf) which cover three different ways to read the contents of a file. ### Check your results You can confirm the accuracy of your results by opening the file(s) your function reports and confirming those file do in fact contain the string `treasure!`. Once you're confident your function is producing the correct answer, you can also check it against the solution which you can see by clicking here. ### Check again with the pirates folder Run your code on the `pirates` folder, which has several subfolders with various files. Your program should find the files that contain treasure. Click here to see pirates treasure. @include('/labs/lab13/_toc') @stop