> For the complete documentation index, see [llms.txt](https://riteshs4hu.gitbook.io/infosec-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://riteshs4hu.gitbook.io/infosec-notes/language/python/basic/file-handling.md).

# File handling

File handling in Python allows you to **read**, **write**, and **manipulate files**. Python provides a built-in function `open()` to work with files.

***

### **1. Opening and Closing Files**

#### **`open(file, mode)`**

Used to open a file and return a file object.

| Mode  | Description                                                |
| ----- | ---------------------------------------------------------- |
| `'r'` | Read (default). File must exist.                           |
| `'w'` | Write. Creates a new file or overwrites an existing one.   |
| `'a'` | Append. Writes data at the end of the file.                |
| `'x'` | Exclusive creation. Fails if file exists.                  |
| `'b'` | Binary mode (used with other modes, e.g., `'rb'`, `'wb'`). |
| `'t'` | Text mode (default).                                       |
| `'+'` | Read and write mode (e.g., `'r+'`, `'w+'`).                |

**Example:**

```python
f = open('example.txt', 'r')
print(f.read())
f.close()
```

#### **`close()`**

Closes the file and frees up system resources.

```python
f = open('example.txt', 'r')
f.close()
```

> 💡 Always close files after use — or use the **`with`** statement (context manager) which closes the file automatically.

***

### **2. Using `with` Statement (Best Practice)**

```python
with open('example.txt', 'r') as f:
    data = f.read()
    print(data)
# File is automatically closed here
```

***

### **3. Reading Files**

| Method        | Description                                 | Example         |
| ------------- | ------------------------------------------- | --------------- |
| `read(size)`  | Reads the entire file or up to `size` bytes | `f.read(10)`    |
| `readline()`  | Reads one line at a time                    | `f.readline()`  |
| `readlines()` | Reads all lines into a list                 | `f.readlines()` |

**Example:**

```python
with open('example.txt', 'r') as f:
    print(f.read())           # Entire file
    print(f.readline())       # First line
    print(f.readlines())      # List of all lines
```

***

### **4. Writing to Files**

| Method             | Description              | Example                               |
| ------------------ | ------------------------ | ------------------------------------- |
| `write(string)`    | Writes a string to file  | `f.write('Hello\n')`                  |
| `writelines(list)` | Writes a list of strings | `f.writelines(['A\n', 'B\n', 'C\n'])` |

**Example:**

```python
with open('output.txt', 'w') as f:
    f.write('This is a line.\n')
    f.writelines(['Line 1\n', 'Line 2\n'])
```

> ⚠️ **Note:** Using `'w'` mode overwrites the file. Use `'a'` mode to append instead.

***

### **5. File Cursor and Positioning**

| Function                  | Description                         | Example                   |
| ------------------------- | ----------------------------------- | ------------------------- |
| `tell()`                  | Returns current file position       | `f.tell()`                |
| `seek(offset, from_what)` | Moves cursor to a specific position | `f.seek(0)` (go to start) |

**Example:**

```python
with open('example.txt', 'r') as f:
    print(f.read(5))
    print('Cursor position:', f.tell())
    f.seek(0)
    print(f.read(5))
```

> `from_what` values:
>
> * `0`: Beginning of file (default)
> * `1`: Current position
> * `2`: End of file

***

### **6. File Attributes**

Each file object has attributes that provide information about the file.

| Attribute | Description                   | Example    |
| --------- | ----------------------------- | ---------- |
| `name`    | File name                     | `f.name`   |
| `mode`    | Mode in which file was opened | `f.mode`   |
| `closed`  | Checks if file is closed      | `f.closed` |

**Example:**

```python
f = open('example.txt', 'r')
print(f.name)
print(f.mode)
f.close()
print(f.closed)
```

***

### **7. Working with Binary Files**

Use `'b'` in the mode to read/write binary files (like images, executables, etc.).

**Example (Read Binary):**

```python
with open('image.jpg', 'rb') as f:
    data = f.read()
```

**Example (Write Binary):**

```python
with open('copy.jpg', 'wb') as f:
    f.write(data)
```

***

### **8. Handling File Errors**

Use `try-except` to handle file-related exceptions gracefully.

```python
try:
    with open('nonexistent.txt', 'r') as f:
        data = f.read()
except FileNotFoundError:
    print("File not found!")
except IOError:
    print("Error reading file!")
```

***

### **9. Common File Operations**

| Operation                  | Example                                        |
| -------------------------- | ---------------------------------------------- |
| Check if file exists       | `import os; os.path.exists('file.txt')`        |
| Delete a file              | `os.remove('file.txt')`                        |
| Rename a file              | `os.rename('old.txt', 'new.txt')`              |
| Copy file (using `shutil`) | `import shutil; shutil.copy('a.txt', 'b.txt')` |
