Cleo_patra

1. Introduction

The current image has no alternative text. The file name is: CLEOP.jpg

File handling is one of the most important skills in Python. Almost every real-world application needs to read from or write to a file. Python makes file handling simple with built-in functions and context managers.


2. Opening and Closing Files

To work with a file, you first need to open it using the built-in open() function.

# Open a file for reading
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()  # Always close the file

File Modes in Python:

ModeDescription
"r"Read (default) – file must exist
"w"Write – creates new file or overwrites existing
"a"Append – adds new content without deleting old data
"x"Create – fails if file already exists
"b"Binary mode (e.g., images, videos)
"t"Text mode (default)

3. Reading Files

Python offers multiple ways to read a file:

# Read entire file
with open("example.txt", "r") as f:
    data = f.read()
    print(data)

# Read line by line
with open("example.txt", "r") as f:
    for line in f:
        print(line.strip())

# Read specific number of characters
with open("example.txt", "r") as f:
    partial = f.read(10)  # first 10 characters
    print(partial)

4. Writing to Files

# Write (overwrites file if it exists)
with open("example.txt", "w") as f:
    f.write("Hello, Python!\n")
    f.write("File handling is easy.")

# Append new data
with open("example.txt", "a") as f:
    f.write("\nThis line is added at the end.")

5. Working with Binary Files

# Copy an image file
with open("image.jpg", "rb") as src:
    with open("copy.jpg", "wb") as dest:
        dest.write(src.read())

6. Best Practices

✅ Use with open() to ensure files are automatically closed.
✅ Handle errors using try...except.
✅ Always specify the correct encoding (encoding="utf-8") for text files.


7. Example: Word Counter Program

def count_words(filename):
    try:
        with open(filename, "r", encoding="utf-8") as f:
            text = f.read()
            words = text.split()
            return len(words)
    except FileNotFoundError:
        return "File not found."

print(count_words("example.txt"))

8. Summary

  • Use open() with modes (r, w, a, etc.) to work with files.
  • read(), readline(), and iteration allow you to process files.
  • Writing and appending data is simple with "w" and "a" modes.
  • Always use with open() for safe and clean file handling.
  • Python supports text and binary file operations.

⬇️ Download Cleo_patra تحميل Server 1 ⬇️ Download Cleo_patra تحميل Server 2 ⬇️ Download Cleo_patra تحميل Server 3

Related Posts

Tigriptv

Introduction Errors are a normal part of programming. In Python, you will encounter two main types of errors: Python provides a powerful way to handle exceptions so your program doesn’t…

Read more

Hyperhd

📌 What are Regular Expressions (Regex)? Regular Expressions (regex) are powerful tools used to search, match, and manipulate text patterns. Python provides the re module to work with regex. 🔹…

Read more

GO-tv

Introduction JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. It’s widely used in APIs, configuration files, and data storage. Python has a built-in json module…

Read more

Eagle

Lesson 9: Dictionaries in Depth 1. Introduction to Dictionaries Dictionaries are one of the most powerful and flexible data structures in Python.They store data as key-value pairs and are extremely…

Read more

NovaPlayer

Lesson 8: Lists, Tuples, and Sets in Python 1. What is a Dictionary in Python? A dictionary in Python is a collection of key-value pairs. 📌 Example: 2. Creating Dictionaries…

Read more

Akratv

Lesson 7 – Functions and Scope in Python 📘 Introduction In Python, lists, tuples, and sets are three important ways to store collections of items. Each has unique features and…

Read more