Lesson 11: File Handling in Python

๐ŸŽฏ Lesson Objective

To learn how to create, read, write, and manage files in Python using built-in file handling methods.


๐Ÿงฉ 1. What Is File Handling?

File handling allows Python programs to store and retrieve data from files.
Common file types: Text files (.txt), CSV files (.csv), JSON files (.json), etc.


โš™๏ธ 2. Opening a File

Use the open() function to open a file.

file = open("example.txt", "w")  # w โ†’ write mode

File Modes

ModeDescription
rRead (default)
wWrite (creates new or overwrites)
aAppend
xCreate (fails if file exists)
r+Read and write

โœ๏ธ 3. Writing to a File

file = open("example.txt", "w")
file.write("Hello, Python File Handling!\n")
file.write("This is a second line.")
file.close()

๐Ÿ“– 4. Reading from a File

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

โœ… Output:

Hello, Python File Handling!
This is a second line.

๐Ÿ”„ 5. Reading Line by Line

file = open("example.txt", "r")
for line in file:
    print(line.strip())
file.close()

Output:

Hello, Python File Handling!
This is a second line.

โž• 6. Appending to a File

file = open("example.txt", "a")
file.write("\nAdding a new line.")
file.close()

๐Ÿ›ก๏ธ 7. Using with Statement

Automatically closes the file after operations.

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

๐Ÿงฎ 8. Other Useful File Methods

MethodDescriptionExample
read(size)Reads size charactersfile.read(10)
readline()Reads one linefile.readline()
readlines()Reads all lines into a listfile.readlines()
tell()Returns current cursor positionfile.tell()
seek(offset)Moves cursor to positionfile.seek(0)
truncate()Truncates filefile.truncate(10)

๐ŸŒ 9. Real-Life Example โ€“ Logging Messages

with open("log.txt", "a") as log_file:
    log_file.write("User logged in at 10:00 AM\n")

with open("log.txt", "r") as log_file:
    logs = log_file.read()
    print(logs)

Output:

User logged in at 10:00 AM


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *