Day 9: File I/O
Today you'll learn how to work with files in Python—reading from and writing to files—which is a
crucial skill for handling external data, logging, configuration management, and more. We'll cover
the basics of file operations, file modes, and best practices for working with files.
Step 1: Understanding File I/O
What is File I/O?
• Definition:
File I/O (Input/Output) refers to the operations of reading from and writing to files on your
computer's storage.
• Why It Matters:
o Data Persistence: Save and retrieve data even after your program ends.
o Data Processing: Read logs, process text data, and work with CSV or JSON files.
o Automation: Automate tasks like backups, data transformations, and more.
Step 2: Opening and Closing Files
Opening a File
• Function: open()
• Syntax:
• file_object = open("filename", "mode")
• Common Modes:
o "r": Read mode (default). Opens the file for reading.
o "w": Write mode. Opens the file for writing (creates a new file or truncates an existing
one).
o "a": Append mode. Opens the file for appending (adds data at the end without
truncating).
o "r+": Read and write mode. Opens the file for both reading and writing.
Closing a File
• Method: .close()
• Why:
Always close a file after you're done to free up system resources.
• Example:
file = open("example.txt", "r")
# ... work with the file ...
file.close()
Using Context Managers
• Preferred Way:
Using the with statement automatically handles closing the file.
• Example:
with open("example.txt", "r") as file:
data = file.read()
# No need to explicitly close the file
Step 3: Reading from Files
Methods to Read File Contents
1. read():
Reads the entire file as a single string.
with open("example.txt", "r") as file:
content = file.read()
print(content)
2. readline():
Reads one line at a time.
with open("example.txt", "r") as file:
first_line = file.readline()
print(first_line)
3. readlines():
Reads all lines and returns them as a list.
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)
Step 4: Writing to Files
Methods to Write Data
1. write():
Writes a string to the file. Use "w" mode to create/truncate a file or "a" mode to append.
with open("output.txt", "w") as file:
file.write("Hello, File I/O!")
2. writelines():
Writes a list of strings to the file.
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("output.txt", "w") as file:
file.writelines(lines)
Step 5: Hands-On Exercises
Exercise 1: Reading from a File
Task:
• Create a text file named sample.txt with some sample content (e.g., multiple lines of text).
• Write a script to open the file, read its content, and print it to the console.
Sample Code:
# Read from sample.txt and print its contents
with open("sample.txt", "r") as file:
content = file.read()
print("File Content:\n", content)
Exercise 2: Writing to a File
Task:
• Write a script that creates (or overwrites) a file called output.txt.
• Write a message or multiple lines of text into the file.
• Then, read back the file content and print it to confirm.
Sample Code:
# Write data to output.txt
lines = [
"Line 1: Welcome to File I/O in Python.\n",
"Line 2: Writing to files is fun!\n",
"Line 3: End of file.\n"
with open("output.txt", "w") as file:
file.writelines(lines)
# Read back and print the content
with open("output.txt", "r") as file:
data = file.read()
print("Written Content:\n", data)
Exercise 3: Appending Data
Task:
• Write a script that appends a new line to an existing file (or creates a new file if it doesn't
exist) using append mode ("a").
Sample Code:
# Append a new line to output.txt
with open("output.txt", "a") as file:
file.write("Appended line: File I/O is really useful!\n")
# Verify the appended content
with open("output.txt", "r") as file:
updated_data = file.read()
print("Updated File Content:\n", updated_data)
Step 6: Experiment in the Interactive Shell
1. Open the Shell:
python
2. Try Out Commands:
# Write a short text to a new file
with open("temp.txt", "w") as f:
f.write("This is a temporary file.\nIt has two lines.")
# Read and print the content
with open("temp.txt", "r") as f:
print(f.read())
3. Exit the Shell:
exit()
Step 7: Additional Learning Resources
• Python Official Documentation – File I/O:
Python File I/O
• W3Schools – Python File Handling:
W3Schools File Handling