> Source URL: /resources/file-io.guide
# File I/O

File I/O (input/output) lets you read data from files and write data to files.

## Reading a File

Use `open()` with `"r"` for reading, and always use `with` to automatically close the file:

```python
with open("names.txt", "r") as file:
    content = file.read()
    print(content)
```

## Reading Line by Line

```python
with open("names.txt", "r") as file:
    for line in file:
        print(line.strip())
```

_Note: `.strip()` removes the newline character at the end of each line._

## Reading All Lines into a List

```python
with open("names.txt", "r") as file:
    lines = file.readlines()

print(lines)
```

Output (if file contains "Alice", "Bob", "Carol" on separate lines):

```
['Alice\n', 'Bob\n', 'Carol\n']
```

A cleaner version using a loop:

```python
with open("names.txt", "r") as file:
    names = []
    for line in file:
        names.append(line.strip())

print(names)
```

Output:

```
['Alice', 'Bob', 'Carol']
```

## Writing to a File

Use `"w"` mode to write. This creates a new file or overwrites an existing one:

```python
with open("output.txt", "w") as file:
    file.write("Hello!\n")
    file.write("This is line 2.\n")
```

## Appending to a File

Use `"a"` mode to add to the end of a file without erasing it:

```python
with open("log.txt", "a") as file:
    file.write("New entry\n")
```

## File Paths

```python
# Same folder as your script
with open("data.txt", "r") as file:
    content = file.read()

# In a subfolder
with open("data/records.txt", "r") as file:
    content = file.read()
```

_Tip: Use relative paths (like `"data/file.txt"`) so your code works on different computers._

## Working with CSV Files

CSV (comma-separated values) files store table-like data:

```
name,age,major
Alice,20,CS
Bob,21,Math
```

### Reading CSV Manually

```python
with open("students.csv", "r") as file:
    for line in file:
        values = line.strip().split(",")
        print(values)
```

Output:

```
['name', 'age', 'major']
['Alice', '20', 'CS']
['Bob', '21', 'Math']
```

### Using the csv Module

```python
import csv

with open("students.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row["name"] + " is " + row["age"])
```

Output:

```
Alice is 20
Bob is 21
```

### Writing CSV Files

```python
import csv

students = [
    ["Alice", "20", "CS"],
    ["Bob", "21", "Math"]
]

with open("output.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["name", "age", "major"])  # header
    writer.writerows(students)                  # data
```

## Handling Missing Files

```python
import os

if os.path.exists("data.txt"):
    with open("data.txt", "r") as file:
        content = file.read()
else:
    print("File not found!")
```

Or use try/except:

```python
try:
    with open("data.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found!")
```

## Common Mistakes

**Forgetting to use `with`**

```python
# Wrong - file might not close properly
file = open("data.txt", "r")
content = file.read()
file.close()

# Right - file closes automatically
with open("data.txt", "r") as file:
    content = file.read()
```

**Using the wrong mode**

```python
# Wrong - "r" mode can't write
with open("output.txt", "r") as file:
    file.write("Hello")  # Error!

# Right - use "w" to write
with open("output.txt", "w") as file:
    file.write("Hello")
```

**Forgetting newlines when writing**

```python
# Wrong - all on one line
with open("names.txt", "w") as file:
    file.write("Alice")
    file.write("Bob")
# File contains: AliceBob

# Right - add \n for new lines
with open("names.txt", "w") as file:
    file.write("Alice\n")
    file.write("Bob\n")
```

**Not stripping newlines when reading**

```python
# Wrong - names have \n attached
with open("names.txt", "r") as file:
    for line in file:
        print("Hello " + line + "!")
# Output: Hello Alice
#         !

# Right - strip the newline
with open("names.txt", "r") as file:
    for line in file:
        print("Hello " + line.strip() + "!")
# Output: Hello Alice!
```


---

## Backlinks

The following sources link to this document:

- [File I/O Guide](/resources/resources.index.llm.md)
- [File Operations](/unit-2/projects/02-archive-audit/tickets/signals.ticket.llm.md)
- [File Operations](/unit-2/projects/02-archive-audit/tickets/simulations.ticket.llm.md)
- [File Operations](/unit-2/projects/02-archive-audit/oracle-handbook.guide.llm.md)
- [File Operations](/unit-2/projects/02-archive-audit/tickets/nodes.ticket.llm.md)
- [File Operations](/unit-2/projects/03-architects-index/tickets/signals.ticket.llm.md)
- [File Operations](/unit-2/projects/03-architects-index/oracle-handbook.guide.llm.md)
- [File Operations](/unit-2/projects/03-architects-index/tickets/nodes.ticket.llm.md)
- [File Operations](/unit-2/projects/03-architects-index/tickets/simulations.ticket.llm.md)
- [File Operations](/unit-2/projects/04-oracle/oracle-handbook.guide.llm.md)
