> ## Documentation Index
> Fetch the complete documentation index at: https://rajanand.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Python: Working with Files

## 1. **What is File Handling?**

* **File handling** refers to reading from and writing to files in Python.
* Files are used to store data persistently, even after the program ends.
* Python provides built-in functions and methods to work with files.

## 2. **Opening a File**

* Use the `open()` function to open a file.
* Syntax: `open(filename, mode)`
* **Modes**:
  * `"r"` : Read mode (default). Opens the file for reading.
  * `"w"` : Write mode. Opens the file for writing (creates a new file or overwrites an existing file).
  * `"a"` : Append mode. Opens the file for appending (writes data to the end of the file).
  * `"x"` : Exclusive creation mode. Creates a new file but raises an error if the file already exists.
  * `"b"` : Binary mode (e.g., `"rb"`, `"wb"`).
  * `"+"` : Read and write mode (e.g., `"r+"`, `"w+"`).

**Example**:

```python theme={"system"}
file = open("example.txt", "r")
```

## 3. **Closing a File**

* Always close a file after working with it using the `close()` method.
* This releases system resources and ensures data is properly saved.

**Example**:

```python theme={"system"}
file = open("example.txt", "r")
# Perform file operations
file.close()
```

## 4. **Using `with` Statement**

* The `with` statement automatically closes the file after the block of code is executed.
* It is the recommended way to work with files.

**Example**:

```python theme={"system"}
with open("example.txt", "r") as file:
    # Perform file operations
    content = file.read()
```

## 5. **Reading from a File**

### **1. `read()`**

* Reads the entire content of the file as a string.

**Example**:

```python theme={"system"}
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
```

### **2. `readline()`**

* Reads a single line from the file.

**Example**:

```python theme={"system"}
with open("example.txt", "r") as file:
    line = file.readline()
    print(line)
```

### **3. `readlines()`**

* Reads all lines from the file and returns them as a list.

**Example**:

```python theme={"system"}
with open("example.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())  # Remove newline characters
```

## 6. **Writing to a File**

### **1. `write()`**

* Writes a string to the file.

**Example**:

```python theme={"system"}
with open("example.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a new line.")
```

### **2. `writelines()`**

* Writes a list of strings to the file.

**Example**:

```python theme={"system"}
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("example.txt", "w") as file:
    file.writelines(lines)
```

## 7. **Appending to a File**

* Use the `"a"` mode to append data to the end of a file.

**Example**:

```python theme={"system"}
with open("example.txt", "a") as file:
    file.write("This is appended text.\n")
```

## 8. **Working with Binary Files**

* Use the `"b"` mode to read or write binary data (e.g., images, videos).

**Example**:

```python theme={"system"}
with open("image.png", "rb") as file:
    binary_data = file.read()
```

## 9. **File Methods and Attributes**

### **1. `seek()`**

* Moves the file pointer to a specific position.

**Example**:

```python theme={"system"}
with open("example.txt", "r") as file:
    file.seek(5)  # Move to the 5th byte
    content = file.read()
    print(content)
```

### **2. `tell()`**

* Returns the current position of the file pointer.

**Example**:

```python theme={"system"}
with open("example.txt", "r") as file:
    file.read(10)
    position = file.tell()
    print(f"Current position: {position}")
```

### **3. `truncate()`**

* Resizes the file to a specified size (in bytes).

**Example**:

```python theme={"system"}
with open("example.txt", "r+") as file:
    file.truncate(10)  # Truncate to 10 bytes
```

## 10. **Additional Examples**

### **1. Reading a File**

```python theme={"system"}
with open("names.txt", "r") as file:
    names = file.readlines()
    for name in names:
        print(f"Hello, {name.strip()}!")
```

### **2. Writing to a File**

```python theme={"system"}
names = ["Raj\n", "Ram\n", "Anand\n", "Bala\n"]
with open("names.txt", "w") as file:
    file.writelines(names)
```

### **3. Appending to a File**

```python theme={"system"}
with open("names.txt", "a") as file:
    file.write("Karthik\n")
```

### **4. Reading and Writing Binary Data**

```python theme={"system"}
with open("image.png", "rb") as file:
    binary_data = file.read()

with open("copy_image.png", "wb") as file:
    file.write(binary_data)
```

## 11. **Best Practices**

* Always use the `with` statement to ensure files are properly closed.
* Handle exceptions (e.g., `FileNotFoundError`) when working with files.
* Use meaningful file names and organize files in directories.
* Avoid hardcoding file paths; use relative paths or configuration files.

**Example**:

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