# Working with Files

Opening a file with Python we need to close it as well.

```python
# Open a new file object for writing only
myfile = open("/tmp/newfile.txt", "w")

# Use the write method to add data to the file
myfile.write("Here is my message.\n")

# The "\n" must be added to separate lines on the file
myfile.write("Here is my second message.")

# We must close out the file object in order to properly close the object
myfile.close()
```

Instead, we can use a `with` codeblock which will automatically handle closing the file once we're done with it.

```python
with open("/tmp/newfile.txt", "r") as myfile:
    for line in myfile:
        print(line)

with open('/tmp/cars.txt', 'r') as cars:
    print(cars.read())
```

We can read all lines of a file into a list for easy use. We need to strip the newline as well.

```python
def fileList(file):
    with open(file) as f:
        lines = f.readlines()
        clean = [ line.strip() for line in lines ]
    return clean
```


---

# 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://notes.m4lwhere.org/programming/python/working-with-files.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.
