# File I/O

{% embed url="<https://youtu.be/s-t38b22UMQ>" %}

## Files

Programs become more useful and interesting when they can interact with data that exists outside of the program. Almost all of the websites that you use store your data for their service in some kind of database or file system. That is how they can give you a persistent service. If we are going to be able to right persistent programs then we need to learn more about storing data. Databases are more of an advanced concept but for right now, the file system will do just fine.

## Reading and Writing Files

Python makes interacting with files very simple. The built-in `open()` function provides us with a way to get a file object we can use.

```python
file_obj = open('filename', 'r')
```

The [`open()`](https://docs.python.org/2/library/functions.html#open) function takes a filename (string) and a mode (string) and returns a file object.

The modes you give it allow you to do different things with the file object. Below is a table of what is possible:

| Mode       | Capability     |
| ---------- | -------------- |
| r          | read           |
| w          | write          |
| a          | append to file |
| r+, w+, a+ | read & write   |
| b          | binary         |

Please read the documentation for more information on the modes. To avoid messing things up you typically don't want to open a file with more permissions than you need. It's up to you though what you decide.

Now that you have a file object, you can read from and write to the file you opened (assuming you used the appropriate mode). The [File Object](https://docs.python.org/2/library/stdtypes.html#bltin-file-objects) has many functions that can let you do a lot of complex operations but the simple ones you should know about are: [`read()`](https://docs.python.org/2/library/stdtypes.html#file.read), [`readline()`](https://docs.python.org/2/library/stdtypes.html#file.readline), [`readlines()`](https://docs.python.org/2/library/stdtypes.html#file.readlines), [`write()`](https://docs.python.org/2/library/stdtypes.html#file.write), [`writelines()`](https://docs.python.org/2/library/stdtypes.html#file.writelines), and [`close()`](https://docs.python.org/2/library/stdtypes.html#file.close). The read functions ending in ...line(s) read the file and separate each line (using the [newline character](https://en.wikipedia.org/wiki/Newline) `'\n'`). `writelines()` takes a list and writes each element in the list as a separate line. These are really handy helper functions that you can use to avoid writing a `for` loop to read and write files.

One thing you should always remember when dealing with files is that you should always close them when you are finished. If you fail to close a file, then you are taking up resources on the computer and other programs might fail because you are a hog.

## The With Block

Since it can sometimes be a huge pain to remember to close resources Python has created a special block that will close resources when the block ends. The `with` block lets you open a file and use it to do whatever you want and then will close the file for you when you're finished.

```python
with open('filename', 'r') as f:
  lines = f.readlines()
```

Remember the scoping rules for `lines` since it is within the `with` block. If an error were to occur while opening the file, then `lines` would not be declared. You can get around that by declaring `lines` outside of the block.

```python
lines = None
with open('filename', 'r') as f:
  lines = f.readlines()
```

You could then catch any file I/O errors using a try/except block.

```python
lines = None
try:
  with open('filename', 'r') as f:
    lines = f.readlines()
except IOError as e:
  print(str(e))

for line in lines:
  recite(line)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://programming.reedcwilson.com/lesson-4/file-io.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
