Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Maths Notes Class 12
  • NCERT Solutions Class 12
  • RD Sharma Solutions Class 12
  • Maths Formulas Class 12
  • Maths Previous Year Paper Class 12
  • CBSE Notes
  • Class 12 Syllabus
  • Class 12 Revision Notes
  • Physics Notes Class 12
  • Chemistry Notes Class 12
  • Biology Notes Class 12
Open In App
Next Article:
CBSE Class 12th Computer Science Unit 2 Notes: Computer Networks
Next article icon

CBSE Class 12th Computer Science Unit 1 Notes: Computational Thinking and Programming

Last Updated : 06 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

CBSE Class 12th Unit 1: Computational Thinking and Programming is a crucial part of the curriculum for Class 12th students, as outlined in the latest CBSE 2024-25 syllabus.

This unit is designed to provide a solid foundation in various essential topics, ensuring students are well-prepared for their board exams and future endeavors in computer science.

Here's a comprehensive overview of the key concepts covered in the CBSE Class 12th CS Unit 1 notes:

  • Revision of Python topics covered in Class XI: Refreshing the fundamental concepts learned in the previous year.
  • Functions: Understanding different types of functions (built-in, module-defined, user-defined), creating user-defined functions, and exploring arguments, parameters, and scopes (global and local).
  • Exception Handling: Introduction to handling exceptions using try-except-finally blocks to manage errors effectively.
  • Introduction to Files: Learning about different types of files (Text, Binary, CSV) and understanding relative and absolute paths.
    • Text File: Opening and closing text files, understanding text file open modes, writing/appending data, reading data, and using seek-and-tell methods.
    • Binary File: Basic operations on binary files, importing the pickle module, using dump() and load() methods, and performing read, write, search, append, and update operations.
    • CSV File: Importing the csv module, opening and closing CSV files, writing data using writer(), writerow(), writerows(), and reading data using reader().
  • Data Structure: Understanding stacks, performing push and pop operations, and implementing stacks using lists.

This guide will provide detailed explanations and examples for each topic, ensuring Class 12th students are confident and well-prepared in computational thinking and programming according to the latest CBSE 2024-25 curriculum.

Table of Content

  • Revision of Python topics covered in Class XI
  • Functions
  • Exception Handling
  • Introduction to Files
  • Text File
  • Binary file
  • CSV file
  • Data Structure
  • Distribution of Marks: CBSE Class 12th Computer Science Unit 1

Revision of Python topics covered in Class XI

For a comprehensive review of Python topics from Class XI, including data types, control structures, functions, and more, check out our dedicated article on Python revision for Class 12th students.

Python Topics Covered in Class XI

  1. Basics of Python Programming
  2. Data Types and Variables
  3. Operators and Expressions
  4. Control Structures
  5. Functions
  6. Strings
  7. Lists
  8. Tuples
  9. Dictionaries
  10. Sets
  11. Modules and Packages
  12. File Handling
  13. Exception Handling

This shortlist includes the fundamental Python topics that will be revised in Class 12th to ensure a strong foundation for advanced programming concepts. For detailed coverage of each topic, make sure to refer to our comprehensive Python revision guide.

Functions

In Python, a function is a piece of code you can use repeatedly to do a specific job. It helps make your code more organized and less repetitive. You create a function using the def keyword, then give it a name and put any inputs (called parameters) in parentheses. When you want to use the function, you "call" it, and the code inside the function runs.

Here’s an example in Python:

def greet(name):
    return f"Hello, {name}!"

When you call greet("Alice"), it’s like saying, “Hi, Alice!” Just think of it as creating your custom commands that make your code do exactly what you want.

Types of Function (Built-in Functions, Functions Defined in Module, User-Defined Functions)

  • Built-in Functions: These built in functions are the ready-to-go tools in your programming toolkit. They’re already coded and ready for you to use without needing to do any extra work. For instance, in Python, functions like print() to show stuff on your screen or len() to count the number of items in a list are built-in. It’s like having a calculator where you don’t need to set up the math formulas, they're just there, ready to go functions.
  • Functions Defined in Modules: Modules are like libraries or extra toolkits that you can add to your programming environment. They come with their own set of functions, which you can use in your projects. For example, if you’re into math, you might use the math module in Python. Inside it, there’s a function called sqrt() that helps you find the square root of a number. It’s like finding the perfect tool for a specific job from a specialized toolbox.
  • User-Defined Functions: This is where you get to be excellent in your class! You create functions to do exactly what you need. For instance, if you’re writing a game and you want a function to check if a player has won, you can make one from scratch. Just like baking a cake with your favorite ingredients, you decide what goes into your function and what it does. 

Creating User-Defined Function

Creating a user-defined function in Python is like designing your custom tool that fits your exact needs. It’s a way to bundle up a set of instructions and give it a name, so you can use it whenever you need it. Here’s how you can create one, step by step:

  1. Define the Function: Start by using the def keyword followed by the name you want for your function. For instance, if you want a function that adds two numbers, you might call it add_numbers.
  2. Add Parameters: Inside the parentheses, you can define the variables that your function will use. These are called parameters. For our adding function, you’ll need two parameters, say a and b.
  3. Write the Function Body: This is where you put the code that does the actual work. In this case, you’d write code to add the two numbers together and return the result.
  4. Call the Function: Finally, you use the function by calling it and passing the necessary arguments (values) to it.

Here’s a simple example to illustrate:

# Step 1: Define the Function
def add_numbers(a, b):
    # Step 2: Write the Function Body
    result = a + b
    return result
# Step 3: Call the Function
sum = add_numbers(5, 3)
print("The sum is:", sum)

In this example:

  • Define the Function: def add_numbers(a, b): sets up a function named add_numbers that takes two parameters.
  • Function Body: result = a + b adds the two numbers and return result sends back the result.
  • Call the Function: add_numbers(5, 3) uses the function with 5 and 3 as arguments, and print shows the result.

Creating user-defined functions is like making your recipes or tools. They help you repeat tasks easily without having to rewrite code. Plus, they make your code cleaner and easier to understand—just like having a neatly organized workspace makes doing tasks more enjoyable!

Arguments and Parameters

Parameters: Think of parameters as the ingredients you need for a recipe. They’re placeholders defined in the function's definition. When you create a function, you set up these placeholders to accept values later. For example:

def make_smoothie(fruit, liquid):
    # 'fruit' and 'liquid' are parameters
    smoothie = f"Blend {fruit} with {liquid}."
    return smoothie

1. Here, fruit and liquid are parameters. They don’t have specific values yet, they’re just waiting to be filled in.

Arguments: Arguments are the actual values you pass into the function when you call it. They’re like the specific ingredients you choose for your smoothie. Using the previous example:

my_smoothie = make_smoothie("banana", "milk")

2. Here, "banana" and "milk" are arguments. They’re the real ingredients you’re using in your smoothie recipe.

To put it all together:

  • Parameters are like placeholders in your recipe card. They define what kind of ingredients (values) you’ll need.
  • Arguments are the actual ingredients you use when you make the smoothie (call the function).

Default Parameters

Default parameters in programming are like setting up your function with built-in values that it will use if you don’t provide any. They help make functions more flexible and easier to use. Here’s how they work:

Setting Default Values: When you define a function, you can assign default values to some of the parameters. If you call the function without specifying a value for these parameters, it automatically uses the default ones.
For example, let’s create a function that prints a welcome message:

def welcome_message(name="Guest"):
    print(f"Welcome, {name}!")

1. Here, name="Guest" sets "Guest" as the default value for the name parameter.

Using Default Parameters: When you call this function, you can either provide a name or let it use the default value.

welcome_message()          # Output: Welcome, Guest!
welcome_message("Alice")   # Output: Welcome, Alice!

2. In the first call, the function uses the default value "Guest". In the second call, it uses the provided argument "Alice".

Default parameters make your functions more versatile and save you from having to repeat code. It’s a simple way to give your functions a default behavior while still allowing for customization when needed.

Positional Parameters

Positional parameters are like the ordered slots in a function where you place your values when calling it. They must be provided in the same order as they appear in the function definition. Here’s a breakdown of how they work:

Defining Positional Parameters: When you create a function, you list the parameters in a specific order. These parameters will receive the values based on their position when the function is called.
For example, let’s define a function that takes two parameters, a and b:

def multiply(a, b):
    return a * b

1. Here, a and b are positional parameters.

Calling the Function with Positional Parameters: When you call this function, you need to provide arguments in the same order as the parameters.

result = multiply(4, 5)
print(result)  # Output: 20

2. In this call, 4 is assigned to a, and 5 is assigned to b based on their positions.

If you swap the values:

result = multiply(5, 4)
print(result)  # Output: 20

Now, 5 is assigned to a and 4 to b, and the result might be different depending on what your function does.

Positional parameters are straightforward and crucial for many functions because they ensure that values are matched to the correct parts of your function. Just remember the order of arguments matters.

Function Returning Value(s)

When a function returns a value, it’s like giving back the result after performing a task. This makes your function not only perform an action but also provide information or data that can be used later. Here’s how you can work with functions that return values:

Returning a Single Value: Most functions return a single value, which you can use immediately. For example, let’s create a function that calculates the square of a number:

def square(number):
   return number * number

Here, return number * number sends back the result of the calculation. When you call this function:

result = square(4)
print(result)  # Output: 16

1. The function square returns 16, which is then printed out.

Returning Multiple Values: Functions can also return more than one value. This is often done using tuples. For example, a function that returns both the sum and the product of two numbers might look like this:

def sum_and_product(x, y):
    return x + y, x * y

When you call this function:

total, product = sum_and_product(3, 5)
print("Sum:", total)       # Output: Sum: 8
print("Product:", product) # Output: Product: 15

2. Here, sum_and_product returns two values, which are captured in total and product.

Returning values from functions helps you build more flexible and powerful programs. You can use these values to make decisions, perform further calculations, or display results. It’s like having a function do the work and then hand you the results so you can use them however you like.

Flow of Execution

The flow of execution in programming is like following a set of instructions step by step. It determines the order in which statements and commands are executed in your code. Here’s a simple breakdown of how it works:

1. Starting Point: When you run a program, the flow of execution begins at the top of your code and proceeds line by line. This is where your program starts, just like the first step in a recipe or a set of instructions.

2. Sequential Execution: By default, most code executes in sequence. This means the code runs from the first line to the last line, one after the other.

print("Step 1")
print("Step 2")
print("Step 3")

In this example, the output will be:

Step 1
Step 2
Step 3

3. Control Flow Statements: Sometimes, you need your program to make decisions or repeat actions. This is where control flow statements come in:

Conditional Statements (if, elif, else)

These allow your program to choose different paths based on conditions

Here, the program decides which message to print based on the value of age.

age = 18
if age >= 18:
print("You can vote.")
else:
print("You are too young to vote.")

Loops (for, while)

These let your program repeat actions multiple times

for i in range(3):
    print("This is loop iteration", i)

This loop will print the message three times, with i taking values from 0 to 2.

Function Calls: When a function is called, the flow of execution jumps to that function’s code, runs it, and then returns to the point where it was called. This helps organize code and avoid repetition.

def greet(name):
    print(f"Hello, {name}!")
greet("Alice")

The program jumps to the greet function, prints the greeting, and then continues from where it left off.

Understanding the flow of execution is crucial because it helps you predict and control how your program behaves, ensuring it performs the right actions at the right times.

Scope of a Variable (global scope, local scope)

The scope of a variable determines where in your code a variable can be accessed or modified. It’s like figuring out where a certain tool or ingredient can be used in a recipe. Here’s a breakdown of the two main types of scopes in programming:

1. Global Scope: Variables defined in the global scope are accessible from anywhere in your code, both inside and outside functions. They’re like tools you can use in any part of your code.

global_var = "I am global"
def print_global():
    print(global_var)
print_global()  # Output: I am global

Example: In this example, global_var is defined outside any function, so it’s available everywhere in the code, including inside the print_global function.

2. Local Scope: Variables defined inside a function or a block of code are local to that function or block. They can only be accessed from within the function or block where they are defined. They’re like special tools used only for specific tasks.

Example:

def my_function():
    local_var = "I am local"
    print(local_var)
my_function()  # Output: I am local
print(local_var)  # This will raise an error

Here, local_var is defined inside my_function, so it can only be used within that function. Trying to access it outside of my_function will result in an error because local_var doesn’t exist in that broader scope.

Key Points:

  • Global Variables: Accessible everywhere in the code but can be changed from any part of the program, which might lead to unexpected results if not managed carefully.
  • Local Variables: Help manage data within specific functions or blocks, keeping your code modular and less prone to errors related to variable reuse.

Understanding variable scope helps you keep your code organized and prevents issues related to variable conflicts or unintended changes.

Exception Handling

Exception handling is like having a backup plan for when things don’t go as expected in your code. It helps you manage errors gracefully without crashing your program. Here’s a simple introduction to how it works:

  • What Is It?: Exception handling is a mechanism in programming that allows you to deal with unexpected events or errors that occur during the execution of a program. Instead of letting these errors stop your program, you can catch them and respond in a controlled way.
  • Why Use It?: Imagine you're coding a program that divides numbers. What if someone tries to divide by zero? Without exception handling, your program might crash. With exception handling, you can catch this error and provide a friendly message instead.

Basic Components

  • Try Block: This is where you write the code that might cause an error. It’s like the part of your program where you’re doing something risky, like accessing a file or performing calculations.
  • Except Block: This catches the error if something goes wrong in the try block. It lets you handle the error and decide what to do next, such as printing an error message or using default values.
  • Finally Block (optional): This part of the code runs no matter what, whether an error occurred or not. It’s useful for cleaning up resources, like closing files or releasing connections.

Example:

try:
    result = 10 / 0  # This will cause a division by zero error
except ZeroDivisionError:
    print("You can't divide by zero!")
finally:
    print("This will always run.")

In this example:

  • Try Block: Attempts to divide by zero, which will raise an error.
  • Except Block: Catches the ZeroDivisionError and prints a message.
  • Finally Block: Runs regardless of whether an error occurred or not, ensuring any necessary cleanup happens.

Exception handling helps keep your programs running smoothly by catching and managing errors in a controlled way. It’s like having a safety net that allows you to handle unexpected issues and keep your application reliable.

Handling Exceptions Using try-except-finally blocks

Handling exceptions using try, except, and finally blocks in Python helps you manage errors and ensure your program behaves predictably, even when things go wrong. Here’s how each part works:

try Block

  • Purpose: You place the code that might cause an error inside the try block. This is where you write the code that you want to execute and monitor for potential problems.

Example:

try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print(f"Result is: {result}")

Here, you’re trying to convert user input into an integer and then perform a division. If the input isn’t a valid number or is zero, it might cause an error.

except Block

  • Purpose: This block catches and handles specific exceptions that occur in the try block. You can specify different except blocks for different types of errors.

Example:

except ValueError:
    print("That's not a valid number!")
except ZeroDivisionError:
    print("You can't divide by zero!")

Here, ValueError catches cases where the user input isn’t a valid number, and ZeroDivisionError handles the case where the user enters zero, causing a division by zero.

finally Block

  • Purpose: This block runs no matter what happens in the try and except blocks. It’s typically used for clean-up actions that should occur regardless of whether an error happened, like closing files or releasing resources.

Example:

finally:
    print("This will always execute, no matter what.")

In this example, the message in the finally block will print whether or not an exception occurred.

Complete Example:

try:
number = int(input("Enter a number: "))
result = 10 / number
       print(f"Result is: {result}")
except ValueError:
       print("That's not a valid number!")
except ZeroDivisionError:
       print("You can't divide by zero!")
finally:
       print("This will always execute, no matter what.")

Key Points:

  • try: Executes code that might raise an exception.
  • except: Catches and handles specific exceptions.
  • finally: Executes code that should run regardless of whether an exception occurred or not.

Using these blocks helps ensure that your program can handle errors gracefully and complete necessary clean-up tasks, making your code more robust and reliable.

Introduction to Files

Files in programming are like containers where you store data so it can be accessed later. They help you save and retrieve information beyond the runtime of your program. Here’s a simple introduction to working with files:

  • Files: A file is a collection of data stored on a computer or other storage device. It can contain text, images, code, or any other type of data. In programming, files are used to read from or write data to them.
  • Types of Files: Common types include text files (.txt), data files (.csv), and code files (.py for Python scripts)

Opening a File

  • Purpose: To perform any operation on a file, you first need to open it. This gives your program access to the file’s contents.
  • Syntax: You use the open() function to open a file. For example:
file = open("example.txt", "r")
  • Here, "example.txt" is the name of the file, and "r" specifies that you want to open it for reading. Other modes include "w" for writing, "a" for appending, and "b" for binary files.

Reading from a File

  • Purpose: To access and use the data stored in a file.

Example:

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

This code opens a file, reads its entire content into the variable content, prints it, and then closes the file.

Writing to a File

  • Purpose: To save data to a file.
file = open("example.txt", "w")
file.write("Hello, world!")
file.close()

Example:
This code opens a file for writing, writes the string "Hello, world!" to it, and then closes the file. If the file already exists, it will be overwritten. If it doesn’t, it will be created.

Closing a File

  • Purpose: To ensure that changes are saved and resources are released.
  • Example: As shown above, always close a file using file.close() to ensure proper resource management.

Using with Statement

  • Purpose: The with statement simplifies file handling by automatically closing the file when done.
  • Example:
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
  • This code does the same thing as before but automatically handles closing the file, even if an error occurs.

Types of Files (Text file, Binary file, CSV file)

Files come in various types, each suited for different kinds of data and uses. Here’s a look at three common types of files: text files, binary files, and CSV files.

Text Files

  • Description: Text files store data in plain text format. They are easy to read and edit using basic text editors. Each character is represented by a sequence of bytes, usually in ASCII or UTF-8 encoding.
  • Usage: Ideal for storing readable content like documentation, code, or simple data.
  • Example: .txt files, .md (Markdown) files.

Example Code:

# Writing to a text file
with open("example.txt", "w") as file:
    file.write("Hello, world!")
# Reading from a text file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)  # Output: Hello, world!

Binary Files

  • Description: Binary files store data in a format that is not human-readable. They can contain any type of data, including images, audio, video, and executable files. The data is saved in binary format, which is more efficient for large data.
  • Usage: Used for complex data storage like multimedia files, compiled programs, and large datasets.
  • Example: .jpg (image), .exe (executable), .dat (data files).
  • Example Code:
# Writing to a binary file
with open("example.bin", "wb") as file:
    file.write(b'\x00\x01\x02\x03')  # Writing bytes
# Reading from a binary file
with open("example.bin", "rb") as file:
    content = file.read()
    print(content)  # Output: b'\x00\x01\x02\x03'

CSV Files

  • Description: CSV (Comma-Separated Values) files store tabular data in a plain text format where each line represents a row and each value is separated by a comma. They are widely used for data exchange and storage in spreadsheets and databases.
  • Usage: Ideal for storing and exchanging structured data like spreadsheets or databases.
  • Example: .csv files.
  • Example Code:
import csv
# Writing to a CSV file
with open("example.csv", "w", newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "City"])
    writer.writerow(["Alice", "30", "New York"])
    writer.writerow(["Bob", "25", "Los Angeles"])
# Reading from a CSV file
with open("example.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
Output:
['Name', 'Age', 'City']
['Alice', '30', 'New York']
['Bob', '25', 'Los Angeles']

Each file type serves different needs based on how data is represented and used, making it important to choose the right type for your application.

Relative and Absolute Paths

Understanding file paths is crucial for managing files in programming. Paths tell your program where to find or save files. There are two main types of paths: relative and absolute.

Relative Paths

  • Definition: A relative path specifies the location of a file or directory in relation to the current working directory (the directory from which the program is being run). It’s like giving directions based on your current location.
  • Usage: Useful when you want to access files relative to the current directory or when you move your project to a different location but keep the structure the same.
  • Example: If your current directory is /home/user/projects, and you have a file data.txt in a subdirectory files, you would use the relative path files/data.txt to refer to that file.
with open("files/data.txt", "r") as file:
    content = file.read()
    print(content)
  • This path tells the program to look for data.txt inside the files directory within the current directory.

Absolute Paths

  • Definition: An absolute path specifies the full path from the root of the file system to the desired file or directory. It’s like giving complete directions starting from a known point, such as the root of the drive or filesystem.
  • Usage: Useful when you need to specify an exact location of a file, regardless of the current working directory.

Example:

  • On a Unix-based system (like Linux or macOS), an absolute path might look like /home/user/projects/files/data.txt.
  • On a Windows system, it might be C:\Users\user\projects\files\data.txt.
with open("/home/user/projects/files/data.txt", "r") as file:
    content = file.read()
    print(content)
  • This path directs the program to look for data.txt starting from the root directory.

Key Differences

Relative Path:

  • Shorter and more flexible: Works well within a project or when files are moved together.
  • Example: data/file.txt

Absolute Path:

  • Complete and specific: Always points to the exact file location regardless of the current directory.
  • Example: /home/user/documents/data/file.txt (Unix) or C:\Users\user\documents\data\file.txt (Windows)

Understanding when to use relative versus absolute paths helps manage file locations and access more effectively, especially when dealing with complex projects or scripts.

Text File

Opening a text file, text file open modes (r, r+, w, w+, a, a+)

Opening and managing text files in programming involves using different modes that dictate how the file can be accessed and modified. Here’s a breakdown of how to open text files and the various modes available:

Opening a Text File

To open a text file in Python, you use the open() function, which takes two main arguments:

  • Filename: The name of the file you want to open.
  • Mode: A string that specifies the mode in which to open the file.

Basic Syntax:

file = open("filename.txt", "mode")

Text File Open Modes

"r" (Read):

  • Description: Opens the file for reading only. The file must exist; otherwise, it will raise an error.
  • Usage: Use this mode when you only need to read the contents of the file.
Example:
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

"r+" (Read and Write):

  • Description: Opens the file for both reading and writing. The file must exist; otherwise, it will raise an error. It doesn’t truncate the file, so you can overwrite content but not necessarily clear it.
  • Usage: Use this mode if you need to read from and modify the file.
Example:
with open("example.txt", "r+") as file:
    content = file.read()
    file.seek(0)  # Move the cursor to the beginning of the file
    file.write("New content")

"w" (Write):

  • Description: Opens the file for writing only. If the file already exists, it will be truncated (cleared) before writing. If the file doesn’t exist, it will be created.
  • Usage: Use this mode when you want to overwrite the file’s contents or create a new file.
Example:
with open("example.txt", "w") as file:
    file.write("This is a new content.")

"w+" (Write and Read):

  • Description: Opens the file for both writing and reading. If the file exists, it will be truncated before writing. If it doesn’t exist, it will be created.
  • Usage: Use this mode when you need to both read from and write to the file, and you want to start with a fresh file.
Example:
with open("example.txt", "w+") as file:
    file.write("Initial content")
    file.seek(0)  # Move cursor to the beginning of the file
    content = file.read()
    print(content)

"a" (Append):

  • Description: Opens the file for appending. The file is created if it doesn’t exist. Existing content is preserved, and new content is added at the end of the file.
  • Usage: Use this mode when you want to add content to the end of the file without altering the existing content.
Example:
python
with open("example.txt", "a") as file:
    file.write("Appended content.")

"a+" (Append and Read):

  • Description: Opens the file for both appending and reading. The file is created if it doesn’t exist. Existing content is preserved, and new content is added at the end. You can read from anywhere in the file.
  • Usage: Use this mode when you need to read and append to a file.
Example:
with open("example.txt", "a+") as file:
    file.write("More appended content.")
    file.seek(0)  # Move cursor to the beginning of the file
    content = file.read()
    print(content)

Each mode serves different needs depending on how you want to interact with the file, whether you’re reading, writing, or both. Understanding these modes helps ensure you use files effectively and avoid unintended data loss or corruption.

Closing a Text File, Opening a File Using Clause

Closing a Text File

When you open a file in Python, it’s important to close it after you’re done working with it. Closing a file releases any system resources used and ensures that all changes are saved properly.

Why Close a File?

  • Resource Management: Closing a file frees up system resources that were allocated for the file operation.
  • Data Integrity: Ensures that any data written to the file is properly saved and not lost.

How to Close a File: You use the close() method of the file object to close the file.

Example:

file = open("example.txt", "w")
file.write("Hello, world!")
file. close()  # Important to close the file after writing

Opening a File Using the Clause

Using the with statement to open a file is a best practice in Python because it automatically handles file closing for you, even if an error occurs during file operations. This approach is cleaner and reduces the risk of leaving files open accidentally.

How It Works:

  • The with statement creates a context for the file operation. Once the block inside the statement is exited, the file is automatically closed.

Example:

# Writing to a file using the with clause
with open("example.txt", "w") as file:
    file.write("Hello, world!")
    # No need to call file.close() explicitly
# Reading from a file using the with clause
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

In this example:

  • When you use open("example.txt", "w") as a file, the file is opened for writing. After the block of code inside the with statement completes, the file is automatically closed.
  • Similarly, with open("example.txt", "r") as a file opens the file for reading, and it will be closed automatically after reading the content.

Advantages of Using With

  • Automatic Closing: Ensures the file is closed properly, reducing the risk of file corruption or resource leaks.
  • Exception Handling: Even if an error occurs within the block, the file is still closed properly.
  • Cleaner Code: Reduces the amount of code needed to manage file operations.

Using the with statement is a more Pythonic way to handle files, making your code safer and more readable.

Writing/Appending Data to a Text File Using write() and writelines()

When working with text files in Python, you often need to write or append data to them. You can use write() and writelines() methods to achieve this. Here’s how they work and when to use each:

Writing Data with write()

  • Description: The write() method is used to write a single string to a file. If the file is opened in write mode ("w" or "w+"), it will overwrite the existing content of the file. If opened in append mode ("a" or "a+"), it will add the content at the end.
  • Usage: Use write() when you need to write a single string or data chunk to a file.

Example:

# Writing to a file
with open("example.txt", "w") as file:
    file.write("Hello, world!\n")
    file.write("This is a new line.")

In this example:

  • The write() method writes "Hello, world!\n" to the file, followed by "This is a new line.".
  • The \n character creates a new line in the file.

Appending Data with write()

  • Description: When using write() in append mode ("a" or "a+"), it adds the new content at the end of the file without affecting existing data.

Example:

# Appending to a file
with open("example.txt", "a") as file:
    file.write("\nAdding a new line at the end.")

In this example:

  • The new line "Adding a new line at the end." is added to the end of the file without modifying existing content.

Writing Multiple Lines with writelines()

  • Description: The writelines() method writes a list of strings to a file. Each string in the list is written as-is without additional new lines between them, so you need to include \n in the strings if you want line breaks.
  • Usage: Use writelines() when you have multiple lines of text and want to write them all at once.

Example:

lines = ["First line.\n", "Second line.\n", "Third line.\n"]
# Writing multiple lines to a file
with open("example.txt", "w") as file:
    file.writelines(lines)

In this example:

  • The writelines() method writes each string in the lines list to the file, preserving the line breaks defined in the strings.

Key Differences

  • write():
    • Writes a single string at a time.
    • You need to handle line breaks manually.
    • Can be used in both write and append modes.
  • writelines():
    • Writes a list of strings to the file.
    • No automatic line breaks between entries; include \n in each string if needed.
    • Typically used in write mode.

By choosing the appropriate method based on your needs, you can effectively manage file writing and appending operations.

Reading From a Text File Using Read()

Reading from a text file using the read() method in Python allows you to retrieve the entire content of the file as a single string. Here's how you can use it effectively:

Using read()

  • Description: The read() method reads the entire content of a file and returns it as a string. This method is useful when you want to load the whole file content at once.
  • Usage: Typically used when you need to read the entire file, especially if the file size is manageable and fits into memory.

Basic Example

Here’s a basic example demonstrating how to use read():

# Open the file in read mode
with open("example.txt", "r") as file:
    content = file.read()  # Read the entire file content
    print(content)  # Print the content

Explanation:

  • open("example.txt", "r"): Opens the file example.txt in read mode.
  • file.read(): Reads the entire content of the file.
  • print(content): Displays the file content on the screen.

Reading Specific Amount of Data

You can also specify the number of characters to read by providing an argument to read(). If you provide a number, read(n) will read up to n characters from the file.

Example:

with open("example.txt", "r") as file:
    partial_content = file.read(10)  # Read the first 10 characters
    print(partial_content)  # Print the partial content

Explanation:

  • file.read(10): Reads up to 10 characters from the file.

Reading After Previous Reads

If you call read() multiple times, it continues reading from where it left off.

Example:

with open("example.txt", "r") as file:
    first_part = file.read(5)  # Read the first 5 characters
    second_part = file.read(5)  # Read the next 5 characters
    print("First part:", first_part)
    print("Second part:", second_part)

Explanation:

  • file.read(5): Reads the first 5 characters.
  • file.read(5): Reads the next 5 characters, starting where the last read left off.

Important Points

  • End-of-File: When read() reaches the end of the file, it returns an empty string.
  • File Handling: Always use with to open files. It ensures the file is properly closed after operations, even if an error occurs.
  • Memory Considerations: If dealing with very large files, consider using other methods like readline() or iterating over the file object to avoid loading the entire file into memory at once.

Using read() is straightforward for accessing the full content of a text file and is handy when you need to work with the entire file data as a single string.

readline() and readlines()

When working with text files in Python, readline() and readlines() are two methods that allow you to read the file's content in different ways. Here’s how they work and when to use each:

readline()

  • Description: The readline() method reads one line from the file at a time. It reads until it encounters a newline character (\n) or the end of the file.
  • Usage: Use readline() when you want to read a file line by line and process each line individually.

Example:

# Reading file line by line using readline()
with open("example.txt", "r") as file:
    line = file.readline()  # Read the first line
    while line:
        print(line, end='')  # Print the line, without adding an extra newline
        line = file.readline()  # Read the next line

Explanation:

  • file.readline(): Reads the next line from the file.
  • while line:: Continues reading until the end of the file is reached (when readline() returns an empty string).

readlines()

  • Description: The readlines() method reads all lines from the file and returns them as a list of strings. Each string in the list represents a single line from the file.
  • Usage: Use readlines() when you want to read the entire file into memory and work with each line as a list element.

Example:

# Reading all lines into a list using readlines()
with open("example.txt", "r") as file:
    lines = file.readlines()  # Read all lines into a list
    for line in lines:
        print(line, end='')  # Print each line

Explanation:

  • file.readlines(): Reads all lines and returns them as a list.
  • for line in lines:: Iterates through each line in the list and prints it.

Key Differences

readline():

  • Reads One Line at a Time: Useful for processing files line by line without loading the entire file into memory.
  • Memory Efficient: Ideal for very large files or when you only need to read a specific part of the file.

readlines():

  • Reads All Lines at Once: Loads the entire file into memory as a list of lines.
  • Convenient for Small to Medium Files: Useful when you need to work with all lines at once or when you need to perform operations on the entire file content.

Choosing Between readline() and readlines()

Use readline() if:

  • You are processing a large file.
  • You only need to handle one line at a time.
  • You want to avoid loading the entire file into memory.

Use readlines() if:

  • The file size is manageable and you need to access or manipulate all lines.
  • You prefer working with the entire content at once for simplicity.
  • Both methods are useful depending on the task at hand and the file size, helping you handle file content effectively in different scenarios.

Seek and Tell Methods, Manipulation of Data in a Text File

The seek() and tell() methods in Python provide powerful ways to manipulate the file cursor, allowing you to navigate and manage file data more precisely. Here’s a detailed look at how these methods work and how to use them effectively:

seek()

  • Description: The seek() method is used to move the file cursor to a specific position in the file. This is useful when you want to read or write data from a particular location.
  • Usage: Commonly used to reposition the cursor for reading or writing data, especially after partial reads or writes.
Syntax:
python
file.seek(offset, whence)

offset: The position (in bytes) to move the cursor to, relative to the position specified by whence.

whence: Optional argument specifying the reference position. It can be:

  • 0: The beginning of the file (default).
  • 1: The current file position.
  • 2: The end of the file.

Examples:

Move to the Beginning of the File:

with open("example.txt", "r") as file:
    file.seek(0)  # Move cursor to the start
    content = file.read()
    print(content)

Move to a Specific Position:

with open("example.txt", "r") as file:
    file.seek(5)  # Move cursor to the 5th byte
    content = file.read()
    print(content)

Move to the End of the File

with open("example.txt", "r") as file:
    file.seek(0, 2)  # Move cursor to the end of the file
    end_position = file.tell()  # Get the end position
    print(f"End position: {end_position}")

tell()

  • Description: The tell() method returns the current position of the file cursor. This is useful for tracking where you are in the file or for debugging purposes.
  • Usage: Often used after seek() to confirm the cursor position or to determine how far you’ve read into the file.
Syntax:
python
position = file.tell()

Example:

with open("example.txt", "r") as file:
    file.seek(10)  # Move cursor to the 10th byte
    position = file.tell()  # Get current cursor position
    print(f"Current position: {position}")

Manipulation of Data in a Text File

Manipulating data in a text file involves various operations such as reading, modifying, and writing data at specific positions. Here’s a more detailed look at how you can perform these operations using Python:

1. Reading Data

To work with data in a file, you first need to read it. Depending on your needs, you can read the entire file, specific lines, or chunks of data.

Example:

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

2. Writing Data

You can write data to a file in different modes ("w", "a", "r+") based on whether you want to overwrite, append, or modify existing content.

Examples:

Overwrite Existing Content:

with open("example.txt", "w") as file:
    file.write("New content\n")

Append to Existing Content

with open("example.txt", "a") as file:
    file.write("Appended content\n")

3. Inserting Data at a Specific Position

To insert data at a specific location in a file, you need to read the existing content, modify it, and then write it back. This is because text files don’t support direct insertion; you must rewrite the file with the new content.

Steps:

  1. Read the Content: Load the file content into memory.
  2. Modify the Content: Insert or modify the content as needed.
  3. Write the Modified Content: Write the modified content back to the file.

Example:

Python
# Insert data at a specific position with open("example.txt", "r+") as file:     content = file.read()  # Read the entire file content     insert_position = 10  # Position where you want to insert data     new_content = "Inserted text\n"          # Move the cursor to the insert position     file.seek(insert_position)          # Write the new content     file.write(new_content)          # Optional: Write the remaining content if needed     remaining_content = file.read()     file.seek(insert_position)  # Move cursor back to insert position     file.write(new_content + remaining_content) 

4. Truncating Data

Truncating a file means cutting off its content from a specified position. This is useful for removing unwanted content from the end of a file.

Example:

with open("example.txt", "r+") as file:
    file.seek(10)  # Move cursor to the 10th byte
    file.truncate()  # Remove everything from the 10th byte onwards

5. Replacing Data

To replace a portion of the file, you typically read the entire file, modify the specific part, and then write the entire modified content back to the file.

Example:

Python
with open("example.txt", "r+") as file:     content = file.read()  # Read the entire file content     content = content.replace("old text", "new text")  # Replace old text with new text     file.seek(0)  # Move cursor to the beginning     file.write(content)  # Write the modified content     file.truncate()  # Ensure file is truncated to the new length 

Binary file

Basic operations on a binary file

Binary files are files that contain data in a format that is not human-readable, as opposed to text files which contain data in plain text. In Python, you can perform various operations on binary files, including reading and writing data. Here’s a guide on how to work with binary files:

Basic Operations on Binary Files

1. Opening a Binary File

To work with binary files, you need to open them in binary mode. This is done by adding a "b" to the mode string ("rb" for reading, "wb" for writing, "ab" for appending, etc.).

Example:

# Open a binary file for reading
with open("example.bin", "rb") as file:
    data = file.read()  # Read the entire file content
    print(data)

2. Reading from a Binary File

You can read binary data in chunks or as a whole. Binary files are typically read in bytes, so methods like read(), read(size), and readinto() can be used.

Read the Entire File:

with open("example.bin", "rb") as file:
    data = file.read()  # Read the entire file

Read a Specific Number of Bytes:

with open("example.bin", "rb") as file:
    chunk = file.read(10)  # Read the first 10 bytes

Read Line by Line: For binary files, this is less common, but you can read data into memory and then process it as needed.

3. Writing to a Binary File

To write binary data, open the file in binary write mode ("wb") or append mode ("ab"). Data should be in bytes format.

Examples:

Write Data:
with open("example.bin", "wb") as file:
    data = b'\x00\x01\x02\x03'  # Binary data to write
    file.write(data)

Append Data:

with open("example.bin", "ab") as file:
    additional_data = b'\x04\x05\x06'
    file.write(additional_data)

4. Seek and Tell

You can use seek() to move the file cursor and tell() to get the current position of the cursor.

Seek:

with open("example.bin", "rb") as file:
    file.seek(5)  # Move cursor to the 5th byte
    data = file.read(10)  # Read 10 bytes from that position

Tell:

with open("example.bin", "rb") as file:
    file.seek(10)  # Move cursor to the 10th byte
    position = file.tell()  # Get the current position (should be 10)

5. Truncating a Binary File

Truncate the file to reduce its size or remove data from a specific point. This can be done using the truncate() method.

Example:

with open("example.bin", "r+b") as file:
    file.seek(10)  # Move cursor to the 10th byte
    file.truncate()  # Truncate the file from the 10th byte onward

Open Using File Open Modes (rb, rb+, wb, wb+, ab, ab+)

When working with binary files in Python, you can use various file open modes to control how you read, write, and append data. Each mode serves a different purpose and affects how the file is handled. Here’s a breakdown of the file open modes for binary files:

File Open Modes for Binary Files

"rb" (Read Binary)

  • Description: Opens a file for reading in binary mode.
  • Usage: Use this mode when you only need to read data from the file and do not need to modify it.
Example:
with open("example.bin", "rb") as file:

    data = file.read()  # Read the entire binary content

"rb+" (Read and Write Binary)

  • Description: Opens a file for both reading and writing in binary mode.
  • Usage: Use this mode when you need to read from and write to the same file. The file must exist; if it doesn’t, an error will occur.
Example:
with open("example.bin", "rb+") as file:
    data = file.read(10)  # Read the first 10 bytes
    file.seek(0)  # Move cursor to the start
    file.write(b'\x01\x02\x03')  # Write binary data

"wb" (Write Binary)

  • Description: Opens a file for writing in binary mode. If the file already exists, it will be truncated (i.e., overwritten). If the file does not exist, a new file will be created.
  • Usage: Use this mode when you need to create a new file or overwrite an existing file with binary data.
Example:
with open("example.bin", "wb") as file:
    file.write(b'\x01\x02\x03\x04')  # Write binary data

"wb+" (Write and Read Binary)

  • Description: Opens a file for both writing and reading in binary mode. If the file exists, it will be truncated. If the file does not exist, a new file will be created.
  • Usage: Use this mode when you need to both read and write data, and you don’t mind overwriting the existing file content or creating a new file.
Example:
with open("example.bin", "wb+") as file:
    file.write(b'\x01\x02\x03')  # Write binary data
    file.seek(0)  # Move cursor to the start
    data = file.read()  # Read the written data

"ab" (Append Binary)

  • Description: Opens a file for appending in binary mode. Data is written at the end of the file. If the file does not exist, a new file will be created.
  • Usage: Use this mode when you need to add data to the end of an existing file without modifying the existing content.
Example:
with open("example.bin", "ab") as file:
    file.write(b'\x05\x06\x07')  # Append binary data

"ab+" (Append and Read Binary)

  • Description: Opens a file for both appending and reading in binary mode. Data is written at the end of the file, and you can also read from any part of the file. If the file does not exist, a new file will be created.
  • Usage: Use this mode when you need to both append data to the end of a file and read from it.
Example:
with open("example.bin", "ab+") as file:
    file.write(b'\x08\x09\x0A')  # Append binary data
    file.seek(0)  # Move cursor to the start
  •     data = file.read()  # Read the entire content

Close a Binary File

Closing a binary file in Python is essential to ensure that all data is properly written to the file and that system resources are released. The close() method is used to close a file after you are done with it. Here’s how you can manage closing binary files:

Closing a Binary File

Using close() Method
After performing operations on a file, you should explicitly call the close() method to close the file. This is important for ensuring that all changes are saved and resources are freed.
Example:

file = open("example.bin", "wb")  # Open file in write-binary mode
file.write(b'\x01\x02\x03\x04')  # Write binary data
file.close()  # Close the file

Explanation:

  • file = open("example.bin", "wb"): Opens the file in write-binary mode.
  • file.write(b'\x01\x02\x03\x04'): Writes binary data to the file.
  • file.close(): Closes the file, ensuring that all data is saved and system resources are released.

Using with Statement (Preferred Approach)

The with statement is the preferred way to work with files because it automatically handles opening and closing the file. When the block of code inside the with statement is exited, the file is closed automatically, even if an error occurs.
Example:

with open("example.bin", "wb") as file:  # Open file in write-binary mode
    file.write(b'\x01\x02\x03\x04')  # Write binary data
# File is automatically closed here

Explanation:

  • with open("example.bin", "wb") as file:: Opens the file in write-binary mode and assigns it to the variable file.
  • file.write(b'\x01\x02\x03\x04'): Writes binary data to the file.
  • No need to call file.close(): The file is automatically closed when the block inside the with statement is exited.

Why Closing a File is Important

  • Data Integrity: Ensures that all written data is properly saved to the file. If a file is not closed, some data might not be written.
  • Resource Management: Releases system resources (like file handles) that are used when a file is open. Not closing a file can lead to resource leaks.
  • Avoids Errors: Prevents potential file access errors or corruption.

Import pickle module, dump() and load() method

The pickle module in Python is used for serializing and deserializing Python objects, which means converting Python objects to a byte stream (serialization) and converting byte streams back into Python objects (deserialization). This is particularly useful for saving and loading complex data structures to and from files. The dump() and load() methods are key functions in this process.

Importing the pickle Module

Before using pickle, you need to import it:

import pickle

pickle.dump()

The dump() method is used to serialize a Python object and write it to a file.

Syntax:
pickle.dump(obj, file, protocol=None)
  • obj: The Python object you want to serialize (e.g., a list, dictionary, custom object).
  • file: A file-like object (e.g., an opened file) where the serialized data will be written.
  • protocol: Optional. The protocol version to use for serialization. If omitted, the default protocol is used.
Example:
import pickle
data = {'name': 'Alice', 'age': 25, 'is_student': True}
with open('data.pkl', 'wb') as file:  # Open file in binary write mode
    pickle.dump(data, file)  # Serialize `data` and write to the file

Explanation:

  • data: The Python object to be serialized.
  • with open('data.pkl', 'wb') as file: Opens a file in binary write mode.
  • pickle.dump(data, file): Serializes the data object and writes it to the file.

pickle.load()

The load() method is used to deserialize a Python object from a file, essentially reading the byte stream and converting it back into a Python object.

Syntax:
python
obj = pickle.load(file)
  • file: A file-like object (e.g., opened file) containing the serialized data.
  • Returns: The deserialized Python object.
Example:
import pickle
with open('data.pkl', 'rb') as file:  # Open file in binary read mode
    data = pickle.load(file)  # Deserialize data from the file
print(data)  # Output: {'name': 'Alice', 'age': 25, 'is_student': True}

Explanation:

  • with open('data.pkl', 'rb') as file: Opens a file in binary read mode.
  • pickle.load(file): Reads the serialized data from the file and deserializes it back into a Python object.

Read, write/create, search, append, and update Operations in a Binary File

Handling binary files involves various operations such as reading, writing, searching, appending, and updating data. Here’s a guide on how to perform these operations in binary files using Python:

1. Reading from a Binary File

To read data from a binary file, open the file in binary read mode ("rb"). You can read the entire file or a specific number of bytes.

Read Entire File:

with open("example.bin", "rb") as file:
    data = file.read()  # Read all data from the file
    print(data)

Read Specific Number of Bytes:

with open("example.bin", "rb") as file:
    chunk = file.read(10)  # Read the first 10 bytes
    print(chunk)

2. Writing to or Creating a Binary File

To write data to a binary file, open the file in binary write mode ("wb"). This will create the file if it doesn’t exist or overwrite it if it does.

Write Data:

with open("example.bin", "wb") as file:
    file.write(b'\x01\x02\x03\x04')  # Write binary data

Create and Write Data:

with open("newfile.bin", "wb") as file:
    file.write(b'Hello World')  # Create a new file and write data

3. Searching in a Binary File

Searching in a binary file involves reading the file and looking for specific patterns or bytes. Since binary files don’t have a text-based structure, you need to search through the byte data.

Search for a Byte Pattern:

Python
with open("example.bin", "rb") as file:     data = file.read()     if b'\x02\x03' in data:         print("Pattern found!")     else:         print("Pattern not found.") 

4. Appending to a Binary File

To append data to a binary file, open the file in binary append mode ("ab"). This mode adds data to the end of the file without modifying existing content.

Append Data:

with open("example.bin", "ab") as file:
    file.write(b'\x05\x06\x07')  # Append binary data

5. Updating Data in a Binary File

Updating data involves reading the existing content, modifying it, and then writing it back to the file. This generally requires reading the entire file, making changes, and writing the entire file back.

Update Specific Data:

Python
with open("example.bin", "rb+") as file:     data = file.read()  # Read all data     new_data = data.replace(b'\x02', b'\x99')  # Replace specific bytes      file.seek(0)  # Move cursor to the start     file.write(new_data)  # Write modified data     file.truncate()  # Truncate file to the new length 

CSV file

Import csv module, open/close CSV file

CSV (Comma-Separated Values) files are a popular format for storing tabular data. The csv module in Python provides functions to work with CSV files, allowing you to read from and write to them efficiently. Here’s a guide on how to use the csv module to handle CSV files:

Importing the csv Module

Before you can work with CSV files, you need to import the csv module:

import csv

Opening and Closing a CSV File

To work with CSV files, you need to open them, perform the necessary operations, and then close them. Python's csv module works with file objects, so you use standard file-handling methods to open and close files.

1. Opening a CSV File

You open a CSV file using Python's built-in open() function and pass the file object to the csv module's reader or writer functions.

Example: Opening a CSV File for Reading

import csv

with open('data.csv', mode='r', newline='') as file:  # Open file in read mode

    reader = csv.reader(file)  # Create a CSV reader object

    for row in reader:

        print(row)  # Print each row in the CSV file

Example: Opening a CSV File for Writing

import csv
with open('data.csv', mode='w', newline='') as file:  # Open file in write mode
    writer = csv.writer(file)  # Create a CSV writer object
    writer.writerow(['Name', 'Age', 'City'])  # Write header row
    writer.writerow(['Alice', '30', 'New York'])  # Write data row

2. Closing a CSV File

When using the with statement, the file is automatically closed when the block of code is exited, which is a good practice as it ensures that resources are managed properly. If you’re not using the with statement, you need to manually close the file.

Manual Closing Example:

import csv
file = open('data.csv', mode='r', newline='')  # Open file in read mode
reader = csv.reader(file)  # Create a CSV reader object
for row in reader:
    print(row)  # Print each row
file.close()  # Close the file manually

Key Points

  • Opening: Use open('filename.csv', mode='r') to read and open('filename.csv', mode='w') to write. Include newline='' to handle line breaks correctly in CSV files.
  • Reading: Use csv.reader(file) to read the file. Iterate through the rows to access data.
  • Writing: Use csv.writer(file) to write to the file. Use writerow() to write a single row and writerows() to write multiple rows.
  • Closing: If not using with, call file.close() to close the file manually.

Write into a CSV file using writer(),writerow(),writerows()

Writing data to a CSV file in Python involves using the csv module's writer() function, along with writerow() and writerows() methods. Here’s a detailed guide on how to use these functions:

Using csv. writer()

The csv. writer() function creates a writer object that you can use to write data to a CSV file. You need to open a file in write mode ("w") or append mode ("a"), and then use the writer object to add data to the file.

Writing Data with csv.writer()

1. Writing a Single Row with writerow()

The writerow() method is used to write a single row of data to the CSV file. The row data should be provided as a list or tuple.

Example:

import csv
# Open file in write mode
with open('data.csv', mode='w', newline='') as file:
    writer = csv.writer(file)  # Create a CSV writer object
    # Write a single row
    writer.writerow(['Name', 'Age', 'City'])  # Header row
    writer.writerow(['Alice', '30', 'New York'])  # Data row
    writer.writerow(['Bob', '25', 'Los Angeles'])  # Another data row

Explanation:

  • csv.writer(file): Creates a writer object.
  • writer.writerow(['Name', 'Age', 'City']): Writes the header row.
  • writer.writerow(['Alice', '30', 'New York']): Writes a data row.

2. Writing Multiple Rows with writerows()

The writerows() method is used to write multiple rows at once. You need to provide a list of lists or tuples, where each inner list or tuple represents a row of data.

Example:

import csv
# Open file in write mode
with open('data.csv', mode='w', newline='') as file:
    writer = csv.writer(file)  # Create a CSV writer object
    # Write multiple rows
    rows = [
        ['Name', 'Age', 'City'],  # Header row
        ['Alice', '30', 'New York'],  # Data row
        ['Bob', '25', 'Los Angeles'],  # Another data row
        ['Charlie', '35', 'Chicago']  #Another data row]
    writer.writerows(rows)  # Write all rows at once

Explanation:

  • csv.writer(file): Creates a writer object.
  • rows: A list of lists, where each inner list represents a row.
  • writer.writerows(rows): Writes all rows to the file at once.

Handling Newlines

When opening a CSV file, use newline='' in the open() function to handle newline characters correctly and avoid blank lines between rows.

Read from a csv file using reader()

Reading data from a CSV file in Python using the csv module involves using the csv.reader() function. This function creates a reader object that iterates over lines in the CSV file, providing each row as a list of strings. Here's a detailed guide on how to read from a CSV file:

Importing the csv Module

First, you need to import the csv module:

import csv

Reading from a CSV File

1. Reading All Rows

You can read all rows from a CSV file using the csv.reader() object in a loop. Each row is returned as a list of strings.

Example:

import csv
# Open file in read mode
with open('data.csv', mode='r', newline='') as file:
    reader = csv.reader(file)  # Create a CSV reader object
    # Iterate over rows in the CSV file
    for row in reader:
        print(row)  # Print each row (list of strings)

Explanation:

  • csv.reader(file): Creates a reader object to read the CSV file.
  • for row in reader: Iterates through each row in the file.
  • print(row): Prints the current row as a list of strings.

2. Reading Specific Rows

If you want to read only specific rows or perform operations on certain rows, you can do so by iterating through the rows and adding conditional logic.

Example:

import csv
# Open file in read mode
with open('data.csv', mode='r', newline='') as file:
    reader = csv.reader(file)  # Create a CSV reader object
    # Read and print only rows where the age is greater than 30
    for row in reader:
        if row[1].isdigit() and int(row[1]) > 30:  # Check if the age (second column) is greater than 30
print(row)

Explanation:

  • row[1].isdigit(): Checks if the value in the second column is a digit before converting it to an integer.
  • int(row[1]) > 30: Filters rows where the age is greater than 30.

3. Reading with Headers

If your CSV file includes a header row, you can use the csv.DictReader() function, which reads each row as a dictionary where the keys are the column names.

Example:

import csv
# Open file in read mode
with open('data.csv', mode='r', newline='') as file:
    reader = csv.DictReader(file)  # Create a CSV dict reader object
    # Iterate over rows as dictionaries
    for row in reader:
        print(row)  # Print each row as a dictionary

Explanation:

  • csv.DictReader(file): Reads each row as a dictionary with headers as keys.
  • print(row): Prints each row as a dictionary where keys are column names.
CBSE-Class-12th-Computer-Science-Unit-1-Notes
CBSE Class 12th Computer Science Unit 1 Notes: Computational Thinking and Programming

Data Structure

A data structure is a way of organizing and storing data so that it can be used efficiently. It helps in managing large amounts of data and performing different operations like searching, sorting, and modifying data. Examples of data structures include arrays, linked lists, stacks, and queues. They are essential for writing good programs and solving complex problems.

Stack, operations on stack (push & pop)

A stack is a fundamental data structure used in computer science, known for its Last In, First Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. Think of a stack like a stack of plates: you add and remove plates from the top.

Stack Operations

The primary operations for a stack are:

  1. Push: Add an item to the top of the stack.
  2. Pop: Remove the item from the top of the stack.
  3. Peek/Top: View the item at the top of the stack without removing it (optional, but commonly used).
  4. IsEmpty: Check if the stack is empty (optional, but useful for checking stack status).

Implementing a Stack

You can implement a stack using various programming languages and approaches. Here’s how you can do it in Python using a list:

1. Push Operation

The push operation adds an item to the top of the stack. In Python, you can use the append() method of a list to simulate this.

Example:

stack = []  # Initialize an empty stack
# Push items onto the stack
stack.append(1)
stack.append(2)
stack.append(3)
print(stack)  # Output: [1, 2, 3]

Explanation:

  • stack.append(1): Adds 1 to the top of the stack.
  • stack.append(2): Adds 2 to the top of the stack.
  • stack.append(3): Adds 3 to the top of the stack.

2. Pop Operation

The pop operation removes the item from the top of the stack. You can use the pop() method of a list to perform this operation.

Example:

stack = [1, 2, 3]  # Stack with elements
# Pop items from the stack
top_item = stack.pop()  # Removes and returns the top item
print(top_item)  # Output: 3
print(stack)  # Output: [1, 2]

Explanation:

  • stack.pop(): Removes the top item (3) from the stack and returns it.

3. Peek/Top Operation

The peek operation allows you to view the item at the top of the stack without removing it. This can be done by accessing the last element in the list.

Example:

stack = [1, 2, 3]  # Stack with elements
# Peek at the top item
top_item = stack[-1]  # Accesses the last item
print(top_item)  # Output: 3

Explanation:

  • stack[-1]: Accesses the last item in the stack without removing it.

4. IsEmpty Operation

You can check if the stack is empty by testing if the list is empty.

Example:

stack = []  # Empty stack
# Check if the stack is empty
is_empty = len(stack) == 0
print(is_empty)  # Output: True

Explanation:

  • len(stack) == 0: Checks if the stack has no items.

Implementation of Stack Using list

Implementing a stack using a list in Python is straightforward due to the list's built-in methods, which support stack operations like push and pop. Here's a step-by-step guide to creating a stack using Python's list data structure:

Stack Implementation

1. Define the Stack Class
Create a class called Stack that will encapsulate the stack operations. The stack will use a list to store its elements.

2. Implement Stack Operations
Implement the following methods in the Stack class:

  • push(item): Adds an item to the top of the stack.
  • pop(): Removes and returns the item from the top of the stack.
  • peek(): Returns the item at the top of the stack without removing it.
  • is_empty(): Checks if the stack is empty.

Example Implementation

Python
class Stack:     def __init__(self):         self.stack = []  # Initialize an empty list to store stack elements       def push(self, item):         """Add an item to the top of the stack."""         self.stack.append(item)  # Use list append method to push item       def pop(self):         """Remove and return the item from the top of the stack."""         if not self.is_empty():             return self.stack.pop()  # Use list pop method to remove and return top item         else:             raise IndexError("pop from an empty stack")  # Raise an exception if stack is empty       def peek(self):         """Return the item at the top of the stack without removing it."""         if not self.is_empty():             return self.stack[-1]  # Access the last item in the list         else:             raise IndexError("peek from an empty stack")  # Raise an exception if stack is empty       def is_empty(self):         """Check if the stack is empty."""         return len(self.stack) == 0  # Return True if the stack is empty       def __str__(self):         """Return a string representation of the stack."""         return str(self.stack)  # Return list as string for easy visualization   # Example usage if __name__ == "__main__":     my_stack = Stack()      # Push elements     my_stack.push(10)     my_stack.push(20)     my_stack.push(30)      print("Stack after pushes:", my_stack)     # Peek the top element     print("Top element:", my_stack.peek())      # Pop elements     print("Popped element:", my_stack.pop())     print("Stack after pop:", my_stack)      # Check if the stack is empty     print("Is stack empty?", my_stack.is_empty()) 

Explanation

  • __init__(): Initializes an empty list to hold stack elements.
  • push(item): Adds an item to the top of the stack using append().
  • pop(): Removes and returns the top item using pop(). Raises an IndexError if the stack is empty.
  • peek(): Returns the top item without removing it. Raises an IndexError if the stack is empty.
  • is_empty(): Returns True if the stack is empty, otherwise False.
  • __str__(): Provides a string representation of the stack for easy printing.

Usage

  • Push: my_stack.push(10) adds 10 to the stack.
  • Peek: my_stack.peek() returns 30, the top item.
  • Pop: my_stack.pop() removes and returns 30.
  • Is Empty: my_stack.is_empty() returns False if the stack is not empty.

This implementation leverages Python's list operations to efficiently manage stack functionality while ensuring that common stack-related errors are handled.

Distribution of Marks: CBSE Class 12th Computer Science Unit 1

Here is the detailed Mdistribution of CBSE Class 12th Computer Science Unit 1 that helps students understand the weightage of different topics.
This helps in strategic preparation and focusing on important areas. Here’s the distribution of marks as per the latest CBSE 2024-25 curriculum:

  1. Revision of Python topics covered in Class XI: 8 marks
  2. Functions: 12 marks
  3. Exception Handling: 4 marks
  4. Introduction to Files: 10 marks
  5. Data Structure: 6 marks

This distribution is estimated based on the previous year's syllabus and typical weightage given to each topic

Total Marks: 40

Conclusion

In conclusion, CBSE Class 12th Computer Science Unit 1: Computational Thinking and Programming is crucial for your education. By engaging with CBSE Class 12th Computer Science Unit 1 Notes on Python programming, functions, exception handling, and more, you're preparing for exams and building foundational skills for future careers. This unit enhances your problem-solving and critical thinking, key for success in today’s tech-driven world. Embrace learning and stay curious as you explore these essential topics.


Next Article
CBSE Class 12th Computer Science Unit 2 Notes: Computer Networks

A

akshatvensmf
Improve
Article Tags :
  • Python
  • Computer Science Fundamentals
  • School Learning
  • Class 12
  • CBSE - Class 12
  • Class 12 Computer Science
Practice Tags :
  • python

Similar Reads

    Class 12 Computer Science Notes

    CBSE Class 12th Computer Science Unit 1 Notes: Computational Thinking and Programming
    CBSE Class 12th Unit 1: Computational Thinking and Programming is a crucial part of the curriculum for Class 12th students, as outlined in the latest CBSE 2024-25 syllabus. This unit is designed to provide a solid foundation in various essential topics, ensuring students are well-prepared for their
    15+ min read
    CBSE Class 12th Computer Science Unit 2 Notes: Computer Networks
    CBSE Class 12th Computer Science Unit 2 Notes: Computer Networks provides a thorough overview of essential networking concepts for Class 12th students. Our notes cover everything according to the latest CBSE syllabus for Class 12th Computer Science.These comprehensive notes are designed to ensure st
    15+ min read
    CBSE Class 12th Computer Science Unit 3 Notes: Database Management
    Welcome to our comprehensive CBSE Class 12th Computer Science Unit III Notes on Database Management. According to the latest CBSE guidelines, this unit contributes 30 marks to the CS board exam (2024-25). These third-unit CS notes are the best resource for a complete revision, simplifying complex co
    15+ min read
    CBSE Class 12 Syllabus 2024-25: Subject-wise PDF Download
    CBSE Class 12 Syllabus2024-25 has been released by the Central Board of Secondary Education(CBSE). Students can now download the subject-wise syllabus for CBSE Class 12. This year, CBSE has updated few topics and chapters which we have updated in the article below. Students are advised to go through
    15+ min read
    CBSE Study Material 2024-25 PDF Download
    The Central Board of Secondary Education (CBSE) is one of the most respected and esteemed educational boards in India. CBSE board offer a comprehensive and healthy education to all its students so that they can have enough room to grow intellectually and physically. The CBSE board is renowned for it
    5 min read
    CBSE Class 12 Maths Notes: Chapter Wise Notes PDF 2024
    Mathematics is an important subject in CBSE Class 12th Board Exam. There is a common misunderstanding among students that Math is a complex subject. If students will plan their preparation and revision in right direction, they can score well in Mathematics. For this Purpose, We have curated the Chap
    15+ min read
    CBSE Class 12 Physics Notes 2023-24
    CBSE Class 12 Physics Notes are an essential part of the study material for any student wanting to pursue a career in engineering or a related field. Physics is the subject that helps us understand our surroundings using simple and complex concepts combined. Class 12 physics introduces us to a lot o
    10 min read
    CBSE Class 12 Chemistry Notes
    CBSE Class 12 Chemistry Notes: Chemistry is an important subject in CBSE Class 12th. It is a very scoring exam in board exam as well as IIT JEE entrance. By taking help of this CBSE Class 12th Chemistry notes, you can ace the CBSE Class 12th board exam. GeeksforGeeks has compiled the complete notes
    9 min read
    CBSE Class 12 Business Studies Notes
    Business Studies is a study of how to control and manage an organization effectively and efficiently. After providing the basic knowledge about Business Studies in Class 11 Notes, GeeksforGeeks has designed Notes for Class 12 Business Studies according to the CBSE Syllabus. The mentioned below Chapt
    9 min read
    CBSE Class 12 Macroeconomics Notes
    Macroeconomics deals with the study of the national economy as a whole. In Class 11th notes, we covered the study of individuals through microeconomics, now we will learn about the whole economy through Macroeconomics. GeeksforGeeks has designed Notes for Class 12 Macroeconomics in a way that provid
    6 min read
    CBSE Class 12 Indian Economic Development Notes
    Economic Development is a wider concept than economic growth and deals with the programs, activities, and policies that aim at improving the economic well-being and quality of life of a country. GeeksforGeeks has designed Notes for Class 12 Indian Economic Development in a way that provides detailed
    7 min read
    CBSE Class 12 Accountancy Notes
    Accountancy is a practice through which business transactions are recorded, classified, and reported for the proper and successful running of an organization. GeeksforGeeks Class 12 Accountancy Notes have been designed according to the CBSE Syllabus for Class 12. These revision notes consist of deta
    15 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences