---
# System prepended metadata

title: 206 Notes for Claire

---

# 206 Notes for Claire
## Different ways to open a file
The following three ways all do the exact same thing - they all open up the file and print out each line. There's just some speed/memory difference that happens behind the scenes. If you are interested in this, we can talk more about it after your midterm!
### readlines() 
```=python=
# reading a file
openfile = open('myfile.txt', 'r')

# Tip: readlines() gives you a list of lines in the file! (aka you need an extra variable "lines")
lines = openfile.readlines()
for line in lines:
    print(line)

# remember to close it after your code but BEFORE THE FUNCTION RETURNS
openfile.close()
```

### Iterating through "open()"
```=python=
# reading a file
openfile = open('myfile.txt', 'r')

# Tip: printing "openfile" itself only gives you the file handler!
for line in openfile:
    print(line)

# remember to close it after your code but BEFORE THE FUNCTION RETURNS
openfile.close()
```

### Using "with open()"
```=python=
# reading a file
with open('myfile.txt') as openfile:
    # Tip: the "openfile" variable only works under the "with open" indent!!!
    for line in openfile:
        print(line)

# Tip: you don't need to close file using this method
# with open() closes it for you :D
```