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

Rapid_tv

šŸ”¹ Introduction The Rock, Paper, Scissors Game is a classic hand game that you can easily build in Python. šŸ‘‰ Rules: šŸ”¹ Code Example šŸ”¹ Example Run šŸ”¹ Concepts Learned…

Read more

VOD-ZalHD

šŸ”¹ Introduction The Number Guessing Game is a classic beginner Python project. šŸ”¹ Code Example šŸ”¹ Example Run šŸ”¹ Concepts Learned šŸ”¹ Summary ā¬‡ļø Download VOD-ZalHD ŲŖŲ­Ł…ŁŠŁ„ Server 1 ā¬‡ļø…

Read more

Delux_pro

šŸ”¹ Introduction The To-Do List App is one of the most popular beginner projects. It teaches you how to: šŸ”¹ Code Example šŸ”¹ Features of This App šŸ”¹ Example Run…

Read more

Fam4k

šŸ”° Project Overview A calculator is one of the simplest yet most effective projects to start with in Python.You will learn: āœļø Step 1: Plan the Calculator We need: šŸ–„ļø…

Read more

Speed_HD+

1. Introduction Data visualization helps us understand patterns and insights in data by converting raw numbers into charts and graphs.In Python, the most popular libraries are: 2. Installing Required Libraries…

Read more

Dauo

1. Introduction Web scraping is the process of extracting data from websites. In Python, we commonly use libraries like requests (to fetch web pages) and BeautifulSoup (to parse and extract…

Read more