Class 12 Computer Science Python Text Files
Python File Handling: Your Gateway to Persistent Data
What is File Handling?
Imagine you’re working on a Python program that collects user information or processes data. What happens when you close the program? File handling is how we make data persistent – saving it to stay even after our program stops running!
Think of it like saving your game progress or writing notes in a notebook that you can reopen later. File handling allows your Python programs to:
Remember data between sessions
Share information with other programs
Process large datasets efficiently
Create configuration files and reports
Why Learn File Handling?
Real-World Applications:
β Save user preferences and game scores
β Process log files and data exports
β Create and read configuration files
β Build data analysis pipelines
β Generate reports and documents
What is difference between text, binary and csv file
Here’s a clear breakdown of the differences between text, binary, and CSV files:
π Text Files
Format: Human-readable characters (ASCII or Unicode).
Usage: Stores plain text like documents, code, or logs.
Extensions: .txt, .html, .py, etc.
Editing: Can be opened and edited with any text editor.
Structure: Data is stored line by line, often separated by newline characters.
πΎ Binary Files
Format: Machine-readable, stored as a stream of bytes.
Usage: Stores complex data like images, audio, executables.
Extensions: .exe, .jpg, .mp3, .dat, etc.
Editing: Requires specific software or programs to interpret.
Structure: No standard delimiters; data is encoded in binary format.
π CSV (Comma-Separated Values) Files
Format: Text-based but structured in tabular form.
Usage: Stores spreadsheet-like data; widely used for data exchange.
Extensions: .csv
Editing: Can be opened with text editors or spreadsheet software like Excel.
Structure: Each line represents a row; values are separated by commas.
π Summary Table
| Feature | Text File | Binary File | CSV File |
| Readability | Human-readable | Machine-readable | Human-readable |
| Structure | Plain text | Byte stream | Tabular (comma-separated) |
| Use Case | Logs, code, notes | Images, audio, exes | Data exchange, spreadsheets |
| Editors | Any text editor | Specific software | Text editor or Excel |
What is file mode in python and what are its types
In Python, file mode refers to the way a file is opened and interacted withβwhether you’re reading from it, writing to it, appending data, or working with binary content. You specify the mode as the second argument in the open() function like this:
file = open("example.txt", "r")
Hereβs a breakdown of the main types of file modes:
π Text Modes
| Mode | Description |
|---|---|
'r' |
Read-only. File must exist. |
'r+' |
Read and write. File must exist. |
'w' |
Write-only. Overwrites existing file or creates new one. |
'w+' |
Read and write. Overwrites or creates new file. |
'a' |
Append-only. Adds data to end. Creates file if it doesn’t exist. |
'a+' |
Read and append. Pointer at end. Creates file if it doesn’t exist. |
'x' |
Exclusive creation. Fails if file exists. |
π§ Binary Modes
| Mode | Description |
|---|---|
'rb' |
Read-only in binary mode. File must exist. |
'rb+' |
Read and write in binary mode. File must exist. |
'wb' |
Write-only in binary mode. Overwrites or creates new. |
'wb+' |
Read and write in binary mode. Overwrites or creates new. |
'ab' |
Append-only in binary mode. Creates file if not exist. |
'ab+' |
Read and append in binary mode. Creates file if not exist. |
These modes help you control how data is accessed and manipulated, whether you’re working with text files, images, audio, or other binary formats
How to open a text file in Python
To open a text file in Python, you use the built-in open() function. Here’s the basic syntax:
file = open("filename.txt", "mode")
β Common Modes for Opening Text Files
| Mode | Purpose |
|---|---|
'r' |
Read-only (default). File must exist. |
'w' |
Write-only. Creates new file or overwrites existing. |
'a' |
Append. Adds content to end of file. |
'r+' |
Read and write. File must exist. |
'w+' |
Write and read. Overwrites or creates new file. |
'a+' |
Append and read. Creates file if not exist. |
π Example: Reading a File
with open("example.txt", "r") as file:
content = file.read()
print(content)
π Example: Writing to a File
with open("example.txt", "w") as file:
file.write("Hello, world!")
Using with ensures the file is properly closed after you’re done.
Functions to read data from text file in Python
In Python, there are several functions to read data from a text file, each suited for different use cases. Here are the three main functions used to read data from text files, along with two examples for each:
π 1.Β read( )Β
Reads the entire content of the file as a single string.
β Example 1: Read full content
with open("data.txt", "r") as file:
content = file.read()
print(content)
Use case: When you want to load the whole file into memory.
β Example 2: Read partial content
with open("data.txt", "r") as file:
partial = file.read(10) # Reads first 10 characters
print(partial)
Use case: When you only need a portion of the file.
π 2. readline( )
Reads one line at a time from the file.
β Example 1: Read first line
with open("data.txt", "r") as file:
first_line = file.readline()
print(first_line)
Use case: Useful for headers or line-by-line processing.
β Example 2: Loop through lines
with open("data.txt", "r") as file:
line = file.readline()
while line:
print(line.strip())
line = file.readline()
Use case: Efficient for large files where memory is a concern.
π 3. readlines( )
Reads all lines and returns them as a list of strings.
β Example 1: Read all lines into a list
with open("data.txt", "r") as file:
lines = file.readlines()
print(lines)
Use case: When you want to process each line individually later.
β Example 2: Iterate over list of lines
with open("data.txt", "r") as file:
for line in file.readlines():
print(line.strip())
Use case: Clean and readable way to loop through file content.
Each method has its strengths:
-
read()is great for small files. -
readline()is ideal for streaming or large files. -
readlines()is handy when you want a list of lines.
Functions to Write into Text Files in Python
To write data to text files in Python, you typically use the open() function with a write mode ('w', 'a', or 'w+') and then use methods like write() or writelines() to insert content. Here’s a breakdown with three examples each for the most common writing methods:
βοΈ 1. write() Method
Writes a single string to the file.
β Example 1: Overwrite with a single line
with open("example1.txt", "w") as file:
file.write("Hello, world!\n")
β Example 2: Append a new line
with open("example1.txt", "a") as file:
file.write("This is an appended line.\n")
β Example 3: Write multiple lines one by one
with open("example1.txt", "w") as file:
file.write("Line 1\n")
file.write("Line 2\n")
file.write("Line 3\n")
π 2. writelines() Method
Writes a list of strings to the file.
β Example 1: Write a list of lines
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("example2.txt", "w") as file:
file.writelines(lines)
β Example 2: Append multiple lines
more_lines = ["Fourth line\n", "Fifth line\n"]
with open("example2.txt", "a") as file:
file.writelines(more_lines)
β Example 3: Write lines from a loop
data = [f"Item {i}\n" for i in range(1, 4)]
with open("example2.txt", "w") as file:
file.writelines(data)
π§ͺ 3. Using print() with file argument
A lesser-known but handy way to write to files.
β Example 1: Print to file
with open("example3.txt", "w") as file:
print("Printed line using print()", file=file)
β Example 2: Print multiple lines
with open("example3.txt", "w") as file:
for i in range(3):
print(f"Line {i+1}", file=file)
β Example 3: Append with print
with open("example3.txt", "a") as file:
print("Appended with print()", file=file)
Each method has its own strengths:
-
write()is precise and good for single strings. -
writelines()is efficient for lists. -
print()is flexible and auto-adds newline characters.
