SHARK_PRO

๐Ÿ”ฐ What Is File Handling?

๐ŸŸข Lesson 3

The current image has no alternative text. The file name is: IMG_20250731_020039_edit_335388598372779-scaled.jpg

File handling lets your Python programs interact with files on your computer โ€” read data from them or save data to them.

๐Ÿ“ You can:

  • ๐Ÿ” Read data from files (like .txt, .csv)
  • โœ๏ธ Write or append new data
  • ๐Ÿ—‚๏ธ Use it to store logs, user input, or application data

๐Ÿ“˜ Basic Syntax: open()

pythonCopierModifierfile = open("filename.txt", "mode")
ModePurpose
'r'Read (default)
'w'Write (overwrite file)
'a'Append (add to file)
'x'Create a new file (error if exists)
'b'Binary mode
't'Text mode (default)

๐Ÿ“– Reading a File

โœ… Method 1: Using open() and read()

pythonCopierModifierfile = open("example.txt", "r")
content = file.read()
print(content)
file.close()

๐Ÿ“Œ Important: Always close() the file when done.


โœ… Method 2: Using with (recommended)

pythonCopierModifierwith open("example.txt", "r") as file:
    content = file.read()
    print(content)

โœ” with automatically closes the file when finished.


โœ๏ธ Writing to a File

pythonCopierModifierwith open("output.txt", "w") as file:
    file.write("Hello from Python!\n")
    file.write("This will overwrite the file.")

๐Ÿ“Œ 'w' mode creates a new file or overwrites an existing one.


โž• Appending to a File

pythonCopierModifierwith open("output.txt", "a") as file:
    file.write("\nThis line was added later.")

๐Ÿ“Œ 'a' mode keeps existing content and adds new lines.


๐Ÿ”„ Reading Line by Line

pythonCopierModifierwith open("example.txt", "r") as file:
    for line in file:
        print("๐Ÿ”น", line.strip())

โœ” strip() removes newlines and extra spaces.


๐Ÿง  Exercise 1: Write and Read

  1. Ask the user to enter 3 lines.
  2. Save them to notes.txt.
  3. Then read and display the file content.
pythonCopierModifierwith open("notes.txt", "w") as file:
    for i in range(3):
        line = input(f"Enter line {i+1}: ")
        file.write(line + "\n")

print("\n๐Ÿ“„ File Contents:")
with open("notes.txt", "r") as file:
    print(file.read())

๐Ÿง  Exercise 2: Count Lines in a File

Assume a file students.txt exists. Count how many lines it contains.

pythonCopierModifierwith open("students.txt", "r") as file:
    lines = file.readlines()

print("๐Ÿ“‹ Total lines:", len(lines))

๐Ÿ›  Tip: Handle Missing Files Gracefully

pythonCopierModifiertry:
    with open("missing.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("โŒ File not found.")

๐Ÿ“ Summary

  • Use open("file", "mode") to access files.
  • Always use with open(...) to handle files safely.
  • Modes like 'r', 'w', 'a' define how the file is opened.
  • Use .read(), .write(), and .readlines() to manipulate content.
Code Activate ูƒูˆุฏ ุงู„ุชูุนูŠู„

Username : 0559403251
Password : 1134091580

โฌ‡๏ธ Download SHARK_PRO ุชุญู…ูŠู„ Server 1 โฌ‡๏ธ Download SHARK_PRO ุชุญู…ูŠู„ Server 2

Related Posts

FivG_Pro

๐Ÿ”ฐ What Is a Function? A function is a reusable block of code that performs a specific task.Instead of repeating code, we can write it once and call it whenever…

Read more

Show7_Pro

๐ŸŸข Lesson 6 โ€“ Intermediate Level ๐Ÿ”ฐ What Is a Module? A module is simply a Python file (.py) containing code (functions, variables, classes) you can reuse in other programs….

Read more

GoldiptvPro

๐ŸŸข Lesson 5 โ€“ Intermediate Level ๐Ÿ”ฐ What Are Exceptions? An exception is an error that occurs during the execution of a program.If not handled, it will stop the program…

Read more

Domingo

๐ŸŸข Lesson 4 ๐Ÿ”ฐ What Is OOP? Object-Oriented Programming (OOP) is a programming style where you organize code into objects that contain: Python supports OOP using: ๐Ÿงฑ Example: Why Use…

Read more

ZinaTv

๐ŸŸข Lesson 2 โ€“ Intermediate Level ๐Ÿ”น Python Dictionaries: Storing and Accessing Key-Value Data ๐Ÿ”ฐ What Is a Dictionary? A dictionary in Python is a data structure that stores data…

Read more

Pro_Click

๐Ÿ”ฐ What Are Lists ? A list is an ordered collection of items stored in a single variable. ๐Ÿ“Œ Lists are defined using square brackets []. ๐Ÿงช Example : pythonCopierModifierfruits…

Read more