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

FlyFeditv

๐Ÿ“˜ Introduction In this project, youโ€™ll create a command-line Expense Tracker that allows users to: โœ… Add expenses with category, amount, and descriptionโœ… View total spending and category breakdownโœ… Automatically…

Read more

NetCinFly

๐Ÿ“˜ Introduction In this project, youโ€™ll develop a Student Grades Analyzer in Python that can: This project helps you strengthen your skills with lists, dictionaries, loops, and data analysis logic….

Read more

Eagle_Pro

๐ŸŒ Introduction In this project, youโ€™ll create a Web Scraper App in Python that extracts quotes, authors, and tags from a live website.Youโ€™ll use the BeautifulSoup and Requests libraries to…

Read more

Cobra_Pro

๐ŸŒฆ๏ธ Introduction In this project, youโ€™ll build a Weather App in Python that retrieves live weather information from an online API.Youโ€™ll learn how to work with HTTP requests, JSON data,…

Read more

Show7-Pro

Concepts Covered: ๐ŸŽฏ Objective: Create a simple, text-based contact book application that allows users to: ๐Ÿ’ก Code (contact_book.py): ๐Ÿง  Example Usage Console Output Example: ๐Ÿ’พ Notes โฌ‡๏ธ Download Show7-Pro ุชุญู…ูŠู„…

Read more

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