CMPE 150
Introduction to Computing
Fall 2021
Created by Gökçe Uludoğan
### Files
- Named locations on disk.
- Used to permanently store data
- File operation order:
- Open the file
- Read/write
- Close the file
### Opening files: open(filepath, mode)
```python
f = open('test_file.txt', 'r')
```
**Modes:**
- **'r'** for reading,
- **'w'** for writing,
- **'a'** for appending
### Closing files
After performing file operations, the file needs to be closed properly.
```python
f = open("test_file.txt")
# perform file operations
f.close()
```
To close the file automatically, **with** block can also be used.
```python
with open("test.txt") as f:
# perform file operations
```
### Writing to files
**Modes:**
- **w:** overwrite into the file
- **a:** appends to the existing file
```python
with open('test.txt', 'w') as f:
f.write('First line\n')
f.write('Second line\n')
f.write('Last line\n')
```
### Reading files
**Line by line with a for loop**
```python
with open('test.txt', 'r') as f:
for line in f:
print(line, end='')
```
### Reading files
**Reading the whole file**
```python
f = open('test.txt')
content = f.read()
print(content)
```
### Reading files
**Line by line with readline()**
```python
f = open('test.txt')
print(f.readline())
print(f.readline())
print(f.readline())
```
### Reading files
**Reading all lines**
```python
f = open('test.txt')
print(f.readlines())
```