{"assignment":{"_schema_version":2,"course_id":37,"date_created":"2022-06-28T19:00:00+00:00","date_modified":"2023-10-15T13:08:17.420613+00:00","extra_instructor_files":"{\"&Count-of-monte-cristo.txt\": \"On the 24th of February, 1815, the look\u2013out at Notre\u2013Dame de la Garde signalled the three\u2013master, the Pharaon from Smyrna, Trieste, and Naples.\\n\\nAs usual, a pilot put off immediately, and rounding the Chateau d\u2019If, got on board the vessel between Cape Morgion and Rion island.\\n\\nImmediately, and according to custom, the ramparts of Fort Saint\u2013Jean were covered with spectators; it is always an event at Marseilles for a ship to come into port, especially when this ship, like the Pharaon, has been built, rigged, and laden at the old Phocee docks, and belongs to an owner of the city.\\n\\nThe ship drew on and had safely passed the strait, which some volcanic shock has made between the Calasareigne and Jaros islands; had doubled Pomegue, and approached the harbor under topsails, jib, and spanker, but so slowly and sedately that the idlers, with that instinct which is the forerunner of evil, asked one another what misfortune could have happened on board. However, those experienced in navigation saw plainly that if any accident had occurred, it was not to the vessel herself, for she bore down with all the evidence of being skilfully handled, the anchor a\u2013cockbill, the jib\u2013boom guys already eased off, and standing by the side of the pilot, who was steering the Pharaon towards the narrow entrance of the inner port, was a young man, who, with activity and vigilant eye, watched every motion of the ship, and repeated each direction of the pilot.\\n\\nThe vague disquietude which prevailed among the spectators had so much affected one of the crowd that he did not await the arrival of the vessel in harbor, but jumping into a small skiff, desired to be pulled alongside the Pharaon, which he reached as she rounded into La Reserve basin.\\n\\nWhen the young man on board saw this person approach, he left his station by the pilot, and, hat in hand, leaned over the ship\u2019s bulwarks.\\n\\nHe was a fine, tall, slim young fellow of eighteen or twenty, with black eyes, and hair as dark as a raven\u2019s wing; and his whole appearance bespoke that calmness and resolution peculiar to men accustomed from their cradle to contend with danger.\\n\\n\u201cAh, is it you, Dantes?\u201d cried the man in the skiff. \u201cWhat\u2019s the matter? and why have you such an air of sadness aboard?\u201d\\n\\n\u201cA great misfortune, M. Morrel,\u201d replied the young man,\u2014\u201da great misfortune, for me especially! Off Civita Vecchia we lost our brave Captain Leclere.\u201d\\n\\n\u201cAnd the cargo?\u201d inquired the owner, eagerly.\\n\\n\u201cIs all safe, M. Morrel; and I think you will be satisfied on that head. But poor Captain Leclere\u2014\u201d\\n\\n\u201cWhat happened to him?\u201d asked the owner, with an air of considerable resignation. \u201cWhat happened to the worthy captain?\u201d\", \"&scores.txt\": \"95\\n94\\n93\\n100\\n87\\n45\\n87\\n98\"}","extra_starting_files":"","forked_id":null,"forked_version":null,"hidden":false,"id":1100,"instructions":"## Files\n\n![A picture representing a file is shown, as a document with a filename below it. The filename reads `\"Count-of-monte-cristo.txt\"`. The document has some text in it that is clearly very long.](bakery_sequences_files_monte_cristo_text.png)\n\nYou can think of a file as a string of data.\nIf we know the path and filename of the file, we can use Python to get access to it.\nThen you can process the data as if it were a string, or a list of strings, depending on how you want to use it.\n\n## Opening a File\n\n```python open-example\nbook_path = \"Count-of-monte-cristo.txt\"\nbook_file = open(book_path)\n\n# Boring!\nprint(book_file)\n```\n\nBefore you can access the data in a file, you must use the `open` function.\nThis function consumes the path to the file as a string and returns a `file` object.\nTypically, we store this `file` object into a variable.\nIf you run the example code here, it will not seem very exciting because we have not actually processed the data in the file.\nThe only thing printed is the open file object.\nUntil you tell Python to read the data from the file, the only information you have is that the file is open and ready.\nThe key insight here is that the `file` object is not the same thing as the actual data inside the file.\n\n## Reading Characters from a File\n\n```python read-example\nbook_path = \"Count-of-monte-cristo.txt\"\nbook_file = open(book_path)\n\n# Use the read() method to get the file as a string\nbook_text = book_file.read()\n\nprint(book_text)\n```\n\nThe primary way to get data from a `file` object is to use the \".read()\" method.\nThis method returns the contents of the file as a string.\nCheck out this example where we open the file, read the `file` object, and then print the text of the file.\nNotice how this is a multi-step process: We use the path to open the file, and then we read from that open file.\n\n## Process File Character by Character\n\n```python read-count-example\nbook_path = \"Count-of-monte-cristo.txt\"\nbook_file = open(book_path)\n\n# Use the read() method to get the file as a string\nbook_text = book_file.read()\ncount = 0\nfor character in book_text:\n    count += 1\nprint(count)\n```\n\nWith the string we loaded from the file, we can process the file character by character (just like any other string value).\nIn the example below, we open the file again and count the number of characters using the loop pattern.\n\n## Line-by-line File Iteration\n\n```python iterate-example\nbook_path = \"Count-of-monte-cristo.txt\"\nbook_file = open(book_path)\n\nfor line in book_file:\n    print(line)\n```\n\nOften, we want to process a file line by line.\nBecause a `file` is a sequence of strings (each separated by a new line), we can process it using a `for` loop.\nThe example shown below will process the file line by line, which would be perfect if we wanted to manipulate each line of the file, perhaps to adjust capitalization or convert it to a number.\nNotice that with the `for` loop, we no longer need to use the `.read()` method.\nIf we had combined the `read` and `for` loop, we would have done string iteration, going through the file character by character.\n\n## Line Endings\n\n```python strip-line-endings\nbook_path = \"Count-of-monte-cristo.txt\"\nbook_file = open(book_path)\n\nfor line in book_file:\n    print(line.strip())\n```\n\nThe lines of a file are broken up using new line characters (usually `\\n` although the specific characters can vary by the platform).\nWhen reading a file line by line, the new line characters are included in each line.\nThis is different from the behavior of the `split` method, which does not include the separator character in the split lines.\nTherefore, usually you will want to use the `strip` method to remove the extra whitespace from the end of the line.\n\n## Closing Files\n\n```python close-example\nbook_path = \"Count-of-monte-cristo.txt\"\nbook_file = open(book_path)\n\nprint(book_file.read())\n\n# This is critical!!!\nbook_file.close()\n```\n\nWhen you are done with a file, you should always remember to close it using the `close` method.\nIt's like leaving a house: if you open a door, you need to close the door.\nForgetting to close a file can leak memory resources on older devices and possibly cause data loss.\nPlus, the `close` indicates to anyone reading the program that the file reading phase is finished.\nUsually, Python will automatically close a file when the program ends, but the best practice is to properly close the file yourself to indicate that you are done working with the file.\nOnce a file has been closed, you cannot use the `read` method on the file or iterate through it with a `for` loop.\n\n## File Objects\n\n- **`open`** function that takes a string path and returns an open `file` object\n- **`close`** method of `file` objects that frees up the resource\n- **`read`** method of `file` objects that returns the contents of the file as a string\n- **`for` loop** iteration over the `file` object as a sequence of strings (separated by newlines)\n\nWhen we call the `open` function from before, we were given a `file` object.\nThis is a new type of value, different from strings, lists, or any other type we have seen before.\nThe `file` type has its own unique methods (`read`, `close`) and the ability to be iterated with a `for` loop (just like strings and lists.) You cannot use operators like addition (`+`) or subscripting (square brackets like `[` with an index).\nIn fact, Python has many special types values that are built in.\nWe have previously seen in Unit 5 that we could create our own types using dataclasses; the concept is basically the same here, with other programmers having created special types on our behalf.\nFor now, just remember that the appropriate operations and methods for files are:\n\n## FileNotFoundError\n\n1. Do you have the right filename?\n2. Do you have the right path?\n3. Is the file where you think it is?\n4. Is your program where you think it is?\n5. Ask for help!\n\nFile systems are tricky because everyone has a different setup.\nOften, we misplace files.\nWhen we try to open a file that does not exist, Python raises a `FileNotFoundError` and will suggest the file does not exist.\nTypically, you should check that you know the exact filename, that you are using the path, and that you know where your Python source file is relative to the file you are opening.\n\n## Example File Processing\n\n```python file-processing\nscore_sum = 0\ndata_file = open('scores.txt')\n\nfor line in data_file:\n    score_sum = score_sum + int(line.strip())\n\ndata_file.close()\nprint(score_sum)\n```\n\nProcessing text from books is one possible application for files, but often we want to process a file full of numeric data.\nHere is some example code that will process a list of numbers in a file, each of which represents a score.\nWe are also using the sum pattern we learned about before to add each of those scores together.\nNotice how we must strip off the new lines at the end of each line and then convert that line to a number; when we read data from a file, it comes in as a string.\nRemember, even if a file only contains numbers, the values returned by the `read` method and line-by-line iteration will still just be strings.\nStrings can contain numeric characters, but that does not make those values integers.\nUntil you explicitly convert the contents using the `int` or `float` functions, you have string values.\n\n## Summary\n\n- Data stored in files can be accessed through a programming language like Python.\n- You can call the `open` function in Python with a string filename to get a `file` object.\n- A `file` object has two operations that you can use to access the actual data in the file:\n  - The `.read()` method returns the contents of the file as a string value.\n  - You can use a `for` loop to iterate through a file as a sequence of strings, separating the file based on its new lines.\n- The `.read()` method gives you a string, so you can iterate through the string character by character just like any other string.\n- The line-by-line iteration approach still includes the new line at the end of a line, so usually you will use the `.strip()` method to remove the extra whitespace from the end of each line.\n- When you are done working with a file, you should call the `.close()` method to indicate that the file is no longer necessary and to free up resources.\n","ip_ranges":"","name":"7B2) Files Reading","on_change":"","on_eval":"","on_run":"","owner_id":1,"owner_id__email":"acbart@udel.edu","points":0,"public":true,"reviewed":false,"sample_submissions":[],"settings":"{\n  \"header\": \"Files\",\n  \"youtube\": {\n    \"Bart\": \"gucQQNJZTVw\",\n    \"Amy\": \"YRQOBH846sU\"\n  },\n  \"video\": {\n    \"Bart\": \"https://blockpy.cis.udel.edu/videos/bakery_sequences_files-Bart.mp4\",\n    \"Amy\": \"https://blockpy.cis.udel.edu/videos/bakery_sequences_files-Amy.mp4\"\n  },\n  \"small_layout\": true,\n  \"hide_files\": false,\n  \"summary\": \"In this lesson, you will learn about using Files in Python. Files are an important part of making programs useful, because they allow us to persist information between runs of a program. Commonly, we obtain many different data files, and write a single program that can operate across many files of the same type.\"\n}","starting_code":"","subordinate":true,"tags":[],"type":"reading","url":"bakery_sequences_files_read","version":8},"ip":"216.73.216.157","submission":{"_schema_version":3,"assignment_id":1100,"assignment_version":8,"attempts":0,"code":"","correct":false,"course_id":37,"date_created":"2026-05-20T23:50:33.998065+00:00","date_due":"","date_graded":"","date_locked":"","date_modified":"2026-05-20T23:50:33.998065+00:00","date_started":"","date_submitted":"","endpoint":"","extra_files":"","feedback":"","grading_status":"NotReady","id":2037091,"score":0.0,"submission_status":"Started","time_limit":"","url":"submission_url-c296b545-d7b5-4609-b089-822eb2643f8b","user_id":2044772,"user_id__email":"","version":0},"success":true}
