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 FileCSV File
Readability Human-readable Machine-readable Human-readable
Structure Plain textByte streamTabular (comma-separated)
Use CaseLogs, code, notesImages, audio, exesData exchange, spreadsheets
EditorsAny text editor Specific softwareText 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:

python
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:

python
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

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

πŸ“Œ Example: Writing to a File

python
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

python
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

python
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

python
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

python
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

python
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

python
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

python
with open("example1.txt", "w") as file:
    file.write("Hello, world!\n")

βœ… Example 2: Append a new line

python
with open("example1.txt", "a") as file:
    file.write("This is an appended line.\n")

βœ… Example 3: Write multiple lines one by one

python
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

python
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

python
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

python
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

python
with open("example3.txt", "w") as file:
    print("Printed line using print()", file=file)

βœ… Example 2: Print multiple lines

python
with open("example3.txt", "w") as file:
    for i in range(3):
        print(f"Line {i+1}", file=file)

βœ… Example 3: Append with print

python
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.

error: Content is protected !!