× back

Functional Programming

If-Else Statements in Python

The if-else statement is a fundamental control structure in Python used for decision-making.

Simple if Statement

  • The simplest form of the if statement checks a single condition and executes a block of code if the condition is true.
  • Example:
                    
x = 10
if x > 5:
    print("x is greater than 5")
                    
                

If-Else Statement

  • The if-else statement allows you to execute one block of code if the condition is true and another block if the condition is false.
  • Example:
                    
x = 10
if x % 2 == 0:
    print("x is even")
else:
    print("x is odd")
                    
                

Elif (Else If) Statement

  • The elif statement is used to check multiple conditions after the initial if statement.
  • It allows for a series of conditional checks, and only the block associated with the first true condition will be executed.
  • Example:
                        
x = 10
if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")
                        
                    

Nested If-Else Statements

  • You can nest if-else statements within each other to handle more complex conditions.
  • This allows for hierarchical decision-making based on multiple conditions.
  • Example:
                        
x = 10
if x > 0:
    if x % 2 == 0:
        print("x is positive and even")
    else:
        print("x is positive but odd")
else:
    print("x is not positive")
                        
                    

Loops in Python

Loops are used in Python to execute a block of code repeatedly. There are two main types of loops: for loop and while loop.

For Loop

  • The for loop is used to iterate over a sequence (such as a list, tuple, or string) or to execute a block of code a fixed number of times.
  • It iterates through each item in the sequence and executes the block of code for each item.
  • Example:
                    
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
                    
                

'range()' function

  • 'range()' function generates a sequence of numbers.
  • Syntax: range(start, stop, step)
  • start (Optional): Starting number of the sequence (default is 0).
  • stop (required): Ending number of the sequence. The sequence will go up to, but not include, this number.
  • step (optional): Step size of the sequence (default is 1).

Example:

                        
for i in range(1, 10, 2):
    print(i)
                        
                    

Output:

                        
1
3
5
7
9
                        
                    

While Loop

  • The while loop is used to repeatedly execute a block of code as long as a specified condition is true.
  • It continues iterating until the condition becomes false.
  • Example:
            
i = 0
while i < 5:
    print(i)
    i += 1
            
        

Loop Control Statements

  • Loop control statements allow you to change the execution flow of loops.
  • They include:
    • Break: Terminates the loop prematurely.
    • Continue: Skips the current iteration and continues with the next iteration of the loop.
    • Pass: Placeholder that does nothing. It is used when a statement is required syntactically but you do not want any code to execute.

Break Statement:

  • When the `break` statement is encountered inside a loop, the loop is immediately terminated, and program control moves to the next statement after the loop.
  • It is commonly used to exit a loop early based on certain conditions, avoiding unnecessary iterations.

Example:

        
for num in range(1, 10):
if num == 5:
    break
print(num)  # Output: 1, 2, 3, 4
        
    

Continue Statement:

  • The `continue` statement skips the rest of the current iteration of a loop and moves to the next iteration.
  • It is useful for skipping certain values or processing logic based on specific conditions within a loop.

Example:

        
for num in range(1, 6):
if num == 3:
    continue
print(num)  # Output: 1, 2, 4, 5
        
    

Usage Considerations:

  • The `break` statement is typically used to exit a loop early based on a condition, while the `continue` statement is used to skip specific iterations.
  • Both statements are commonly used in loops to control the flow of execution and optimize code logic.

Functions in Python

Example 1:

                    
# Function to add two numbers
def add_numbers(a, b):
    #This function takes two numbers as input and returns their sum.
    return a + b

# Function to check if a number is even
def is_even(number):
    #This function checks if the given number is even.
    #Returns True if the number is even, False otherwise.
    if number % 2 == 0:
        return True
    else:
        return False

# Function to greet the user
def greet(name):
    #This function takes a name as input and prints a greeting message.
    print(f"Hello, {name}!")

# Testing the functions
num1 = 10
num2 = 5
print(f"The sum of {num1} and {num2} is: {add_numbers(num1, num2)}")

test_number = 7
if is_even(test_number):
    print(f"{test_number} is an even number.")
else:
    print(f"{test_number} is not an even number.")

greet("Alice")
                    
                

Output:

                
The sum of 10 and 5 is: 15
7 is not an even number.
Hello, Alice!
                
            

Scope

In Python, variable scopes determine the visibility and accessibility of variables in different parts of a program. There are three main scopes: local, global, and nonlocal. Understanding these scopes helps in organizing code and preventing naming conflicts.

Local Scope:

  • Variables defined within a function are in the local scope. They are accessible only within that function and are not visible outside. This helps in encapsulating data and logic within functions, enhancing code modularity and readability.
                            
def my_function():
    x = 10  # Local variable
    print(x)  # Accessible within the function

my_function()
                            
                        

Global Scope:

  • Variables defined outside of any function are in the global scope. They are accessible throughout the program, including inside functions. Global variables can be useful for storing data that needs to be accessed from multiple parts of the codebase.
                            
x = 10  # Global variable

def my_function():
    print(x)  # Accessible within the function

my_function()
                            
                        

Nonlocal Scope:

  • Nonlocal scope is used when working with nested functions. It allows accessing variables from the nearest enclosing scope that is not global. This is particularly helpful when dealing with functions defined inside other functions and needing to modify variables from the outer scope.
                            
def outer_function():
    x = 10  # Enclosing scope

    def inner_function():
        nonlocal x  # Access the x from the enclosing scope
        x += 5
        print(x)

    inner_function()

outer_function()
                            
                        

Argument Passing

  • Argument passing refers to how variables or objects are passed to functions when the functions are called.
  • In Python, arguments can be passed by value or by reference, depending on the type of object being passed.

Pass-by-value:

  • Immutable objects (integers, strings, tuples) are passed by value in Python.
  • When passed by value, a copy of the object is created within the function, and modifications to this copy do not affect the original object outside the function.

Example:

                            
def increment(num):
    num += 1
    return num

x = 5
result = increment(x)
print(x)  # Output: 5 (original object is unchanged)
print(result)  # Output: 6 (modified object returned from the function)
                            
                        

Pass-by-Reference:

  • Mutable objects (lists, dictionaries, sets) are passed by reference in Python.
  • When passed by reference, the function receives a reference to the original object. Changes made to the object inside the function affect the original object outside the function.

Example:

                            
def append_item(lst):
    lst.append(4)

my_list = [1, 2, 3]
append_item(my_list)
print(my_list)  # Output: [1, 2, 3, 4] (original list modified inside the function)
                            
                        

Comparison with C++:

  • In C++, argument passing can be explicitly done by value (creating a copy of the object) or by reference (using pointers or references to the original object).
  • Python's pass-by-reference behavior for mutable objects is similar to passing by reference in C++ using pointers or references.
  • However, Python's pass-by-value behavior for immutable objects differs from C++'s pass-by-value, which always creates a copy of the object.

Keyword Arguments in Python

Keyword arguments in Python allow you to specify the name of the parameter you are assigning a value to in the function call. This provides flexibility in the order of arguments and enhances the readability of your code.

Example with Keyword Arguments

            
def greet(name, greeting="Hello", punctuation="!"):
    print(f"{greeting}, {name}{punctuation}")

# Positional arguments
greet("Alice")  # Output: Hello, Alice!
greet("Bob", "Hi")  # Output: Hi, Bob!
greet("Charlie", "Hey", "?")  # Output: Hey, Charlie?

# Keyword arguments (passed by name)
greet(name="David", greeting="Greetings", punctuation=".")  # Output: Greetings, David.
greet(greeting="Hi", name="Eve", punctuation="!!")  # Output: Hi, Eve!!
greet(punctuation="?", name="Frank", greeting="Hey")  # Output: Hey, Frank?

# Mixing positional and keyword arguments
greet("Grace", punctuation="!!")  # Output: Hello, Grace!!
greet("Hannah", greeting="Hi")  # Output: Hi, Hannah!
        
                

Explanation

  • Positional Arguments: The arguments are provided in the same order as the function parameters.
    • greet("Alice") assigns "Alice" to name, uses default "Hello" for greeting, and ! for punctuation.
    • greet("Bob", "Hi") assigns "Bob" to name, "Hi" to greeting, and uses default ! for punctuation.
  • Keyword Arguments (Passed by Name): The arguments are specified by the parameter names, allowing you to provide values in any order.
    • greet(name="David", greeting="Greetings", punctuation=".") assigns "David" to name, "Greetings" to greeting, and . to punctuation.
    • greet(greeting="Hi", name="Eve", punctuation="!!") assigns "Eve" to name, "Hi" to greeting, and !! to punctuation.
  • Mixing Positional and Keyword Arguments: You can mix positional and keyword arguments in the same function call. Positional arguments must come before keyword arguments.
    • greet("Grace", punctuation="!!") assigns "Grace" to name (positional), uses default "Hello" for greeting, and !! for punctuation.
    • greet("Hannah", greeting="Hi") assigns "Hannah" to name (positional), "Hi" to greeting, and uses default ! for punctuation.

Key Points

  • Flexibility: Keyword arguments allow you to skip over some parameters and only specify the ones you want to change.
  • Readability: Using keyword arguments makes it clear what each argument represents, improving code readability.
  • Order Independence: When using keyword arguments, the order of the arguments doesn't matter, as long as the parameter names are specified.

Returning Multiple Integer Values in Python Functions

In Python, you can return multiple integer values from a function by using a tuple.

Example

Here's an example of returning multiple integer values:

                    
def calculate_numbers(a, b):
    sum_result = a + b
    product_result = a * b
    return sum_result, product_result

# Calling the function and capturing each returned value separately
sum_value = calculate_numbers(5, 3)
product_value = calculate_numbers(5, 3)
print(f"Sum: {sum_value}, Product: {product_value}")
                    
                

In this code, the function `calculate_numbers` calculates the sum and product of two integers `a` and `b`. Each value is returned using a separate return statement. When calling the function, each returned value is captured separately.

Advanced Functions

Advanced functions in programming are those that offer specialized capabilities or allow for more concise and efficient coding techniques. One such function type is the lambda function, also known as an anonymous function.

Lambda / Anonymous Function

  • Lambda functions are a concise way to create small, anonymous functions in Python.
  • They are defined using the "lambda" keyword followed by a list of arguments, a colon (:), and an expression. This expression represents the function's logic.
  • Unlike regular functions created with the "def" keyword, lambda functions do not require a name, making them suitable for short, one-time use.
  • The syntax for a lambda function is:
                                
    lambda arguments: expression
                                
                            
    . For example,
                                
    lambda x: x + 1
                                
                            
    defines a lambda function that takes an argument x and returns x + 1.

Usage:

  • Lambda functions are commonly used in situations where a small, temporary function is needed, such as in filtering, mapping, or reducing data.
  • They are often used in conjunction with built-in functions like filter(), map(), and reduce() to perform operations on iterables like lists, tuples, or dictionaries.
  • For example,
                                
    filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])
                                
                            
    uses a lambda function to filter even numbers from the list.

Benefits:

  • Lambda functions offer a more concise syntax compared to traditional function definitions, especially for simple operations.
  • They are often used in functional programming paradigms where functions are treated as first-class citizens.
  • Lambda functions promote code readability when used appropriately and judiciously.

Lambda function example programs

Function to return square of a number:

                            
square = lambda x: x * x 
print("Square of 4 is =", square(4))
                            
                        

Function to add two numbers:

                            
sum = lambda x, y: x + y 
print("Sum of 4 and 5 is =", sum(4, 5))
                            
                        

Function to find largest number between two numbers:

                            
largest = lambda x, y: x if x > y else y
print("Largest between 4 and 5 is =", largest(4, 5))
                            
                        

Lambda function with Filter function

  • The filter function takes a list as arguments.
  • The filter function is called with a new list returned, which contains items for which the function evaluates to "true".
  • The filter function returns an iterator after the items are filtered through a function to test if the item is accepted or not.

Example: Program using the filter function to filter out only even numbers from the given list: [1, 2, 3, 4, 5, 6, 7, 8, 9]

                    
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
newlist = list(filter(lambda x: x % 2 == 0, mylist))
print(newlist)
                    
                

Program using the filter function to print the items greater than 4

                    
mylist = [2, 8, 9, 7, 6, 4, 5, 0] 
result = filter(lambda x: x > 4, mylist)
print(list(result))
                    
                

Lambda function with Map function

  • The map function in Python takes a function and a list. The function is called with all items in the list, and a new list is returned which contains items returned by the function for each item.
  • Map applies a function to all the items in the list. The advantage of lambda operations can be seen when used in combination with the map function.

Program using the map function to double all the items in the list

                    
mylist = [1, 2, 3, 5, 6, 7, 8] 
doublelist = list(map(lambda x: 2 * x, mylist)) 
print(doublelist)
                    
                

Program to separate the letters of the word "hello" and add the letters as items of the list using the map function

                    
result = list(map(lambda x: x, "hello"))
print(result)
                    
                

Lambda function with Reduce function

  • The reduce function applies the same operation to the items of a sequence iteratively until it reduces the sequence to a single value.
  • It uses the result of the first operation as the first argument for the next operation, progressively combining elements.
  • Reducing a sequence with a lambda function is a common pattern for performing cumulative calculations or aggregations.
  • This function is part of the Python standard library and is defined in the "functools" module, so we need to import it before using it.

Program to find the sum of numbers in the list using reduce:

                    
from functools import reduce

mylist = [1, 2, 3, 4, 5, 6, 7] 
# Using reduce with a lambda function to add numbers in the list
sum = reduce(lambda x, y: x + y, mylist) 
print(sum)  # Output: 28 (1 + 2 + 3 + 4 + 5 + 6 + 7 = 28)
                    
                

In this example, the reduce function combines the elements of the list by adding them together using the lambda function (x + y). It starts with the first two elements, adds them, then adds the result with the next element, and so on until all elements are combined into a single sum.

Module

Creating a Module

  • Create a file with a ".py" extension and define functions and variables inside it.
                    
# mymodule.py file 

variable_of_mymodule = 99 

def areaOfSquare(side):
    #Calculate the area of a square
    return side * side

def calculator(a, b, op):
    #Perform basic arithmetic operations
    if op == 1:
        print("Addition is =", a + b)
    elif op == 2:
        print("Subtraction is =", a - b)
    elif op == 3:
        print("Multiplication is =", a * b)
    elif op == 4:
        if b == 0:
            print("Division cannot be performed")
            return
        print("Division is =", a / b)
    else:
        print("Enter a correct operation")
                    
                

Now import it in a separate file and use the functions:

                    
# newfile.py
import mymodule

# Usage example
side_length = 5
print("Area of square with side length", side_length, "is", mymodule.areaOfSquare(side_length))

num1 = 10
num2 = 5
operation = 3  # Multiplication
mymodule.calculator(num1, num2, operation)

# Using the variable_of_mymodule
print("Value of variable_of_mymodule in newfile.py:", mymodule.variable_of_mymodule)
                    
                

If we want to use only one function, we can import it directly:

                    
from mymodule import calculator
                    
                

This imports only the "calculator" function from the "mymodule" module.

If we want to give an alias name to the imported function:

                    
from mymodule import calculator as calc
                    
                

This imports the "calculator" function from the "mymodule" module and gives it an alias "calc". We can then use "calc" instead of "calculator" in our code.

Difference between Library, Module, and Package

  • Library:
    • A collection of pre-written code or functions.
    • Focused on specific domains like math, data analysis, web development, etc.
    • Examples: NumPy, Pandas, Matplotlib, Requests.
  • Module:
    • A single Python file with variables, functions, and classes.
    • Organizes related code into reusable units.
    • Imported using the 'import' statement.
  • Package:
    • A collection of related modules in a directory structure.
    • Contains an __init__.py file to indicate it's a Python package.
    • Allows better organization and management of code in larger projects.
    • Python's standard library is a collection of packages.

Libraries are collections of pre-written code, modules are individual Python files containing code, and packages are directories with related modules. Libraries like NumPy and Pandas offer domain-specific functionality, modules organize code into reusable units, and packages allow better organization in larger projects.

File Handling

How to Open a File?

To open a file in Python, use the following syntax:

                    
file_obj = open("filename", "mode")
                    
                
  • open() function returns a file object or file pointer, which we store in a variable.
  • We can then perform read, write, or close operations using this file object variable.
  • Modes specify the type of operations that can be performed on the file. Choose the mode based on the operation you intend to perform:
    1. r: Opens the file in read mode.
    2. w: Opens the file in write mode. This truncates the file if it exists or creates a new file.
    3. a: Opens the file in append mode. It adds new data at the end of the file without truncating it.
    4. r+: Opens the file for both reading and writing.
    5. w+: Opens the file for both reading and writing. It truncates the file if it exists or creates a new file.
    6. a+: Opens the file for both reading and appending. It creates a new file if it does not exist.
    7. x: Opens the file for exclusive creation. If the file already exists, the operation fails.

seek() function

The seek() function in Python is used to change the current file position within an open file. It is particularly useful when working with files that support random access, such as binary files.

  • Syntax: file.seek(offset, whence)
  • Parameters:
    • offset: The number of bytes to move the file pointer. A positive offset moves the pointer forward, while a negative offset moves it backward.
    • whence: Specifies the reference position for the offset. It can take one of three values:
      • 0 (default): Offset from the beginning of the file
      • 1: Offset from the current file position
      • 2: Offset from the end of the file

The seek() function is commonly used in conjunction with reading or writing operations to navigate to a specific position within a file before performing file operations.

Example:

                    
# Open a file in read mode
file = open("example.txt", "r")

# Move the file pointer to the 5th byte from the beginning
file.seek(5)

# Read and print the content from the current file position
print(file.read())

# Close the file
file.close()
                    
                

File modes:

x mode

  • The "x" mode is used to create a new file. If the file already exists, the operation will fail, preventing accidental overwriting of existing files.
  • This mode is typically used in conjunction with other modes, ensuring that there is always a file available to work on, especially when creating new files.

Example:

                        
# Example of using the "x" mode to create a new file
f1 = open("file_1.txt", "x")
# Now we can use other modes like "w" or "a" to write or append to the file
                    
                

r mode

  • Opens the file in read mode.
  • The file pointer starts at the beginning of the file, meaning it reads from the start of the file.
  • If the file does not exist, it raises an IOError.
  • The "r" mode is the default mode for opening files in Python.
  • To read the content of the file, you can use the read() function.

Example:

                        
# Open the file in "r" mode
f1 = open("file_1.txt", "r")
# f1 = open("file_1.txt") # this will also work

# Read the content of the file
data = f1.read()

# Print the read data
print(data)

# Close the file
f1.close()
                    
                

w mode

  • The "w" mode is used for writing operations, as write operations cannot be performed in read mode ("r").
  • To write content to a file, you open the file in "w" mode.
  • This mode opens the file in write-only mode. It will overwrite the file if it already exists, or create a new file if the file doesn't exist.
  • The file pointer starts at the beginning of the file.

Example:

                        
# Open the file in "w" mode
f1 = open("file_2.txt", "w")  # This file doesn't exist, so a new file will be created; if it exists, its content will be erased.

# Write content to the file
f1.write("Welcome to Jenny's lectures")  # Write the specified content to the file

# Close the file
f1.close()

# You can check the file to see that the content has been written
                        
                    

r+ mode

  • The "r+" mode allows both reading and writing operations on the file.
  • In "r+" mode, if we read first, the cursor will be at the beginning initially. After reading, the cursor will be at the end, allowing us to write content at the end of the file.

Example:

                        
# Open the file in "r+" mode
f1 = open("file_2.txt", "r+")

# First, read from the file (make sure there is content written in the file)
data = f1.read()

# Now, write to the file
f1.write("This is Python lecture")

# Close the file
f1.close()

# You can check the file to see the updated content
                        
                    
  • The write operation in "r+" mode adds the new content at the end of the existing content in the file.

Finding the cursor position:

                        
# Use the tell() method to find the cursor position
cursor_position = f1.tell()
print("Cursor position:", cursor_position)
                        
                    

If you want to place the cursor at a specific position, you can use the seek() method:

                        
# Set the cursor position to a specific location (e.g., position 0)
f1.seek(0)
                        
                    

w+ mode

  • The "w+" mode opens the file for both reading and writing operations, similar to the "r+" mode.
  • The file pointer or cursor exists at the beginning of the file when opened in "w+" mode.
  • If the file already exists, the previous content will be overwritten. If the file doesn't exist, a new file will be created.
  • In contrast to the "r+" mode where a non-existing file raises an error, the "w+" mode simply creates a new file if it doesn't exist.

Example:

                        
# Open the file in "w+" mode
f1 = open("file_4.txt", "w+")

# Write content to the file
f1.write("This is a test file for w+ mode")

# Move the cursor to the beginning of the file
f1.seek(0)

# Read the content from the file
data = f1.read()

# Close the file
f1.close()

# Print the read data to verify
print("Read data:", data)
                    
                

a mode

  • The "a" mode opens the file in append mode, which is different from write mode because it appends new content to the end of the file without overwriting existing content.
  • When a file is opened in "a" mode, the file handler is positioned at the end of the previously written content. If the file already exists, the cursor is placed at the end of that file; if the file doesn't exist, a new file will be created.

Example:

                        
# Open the file in "a" mode
f1 = open("file_5.txt", "a")

# Write content to the file (appends to the end)
f1.write("This is appended content")

# Close the file
f1.close()

# You can check the file to see the appended content
                    
                

a+ Mode

  • The "a+" mode opens the file in append mode with reading capabilities, allowing you to both append new content to the end of the file and read its existing content.
  • When a file is opened in "a+" mode, the file handler is positioned at the end of the previously written content, similar to "a" mode. If the file already exists, the cursor is placed at the end of that file; if the file doesn't exist, a new file will be created.
  • You can use "a+" mode to add new content to the file and then read its entire content, making it a versatile mode for file operations.

Example:

            
# Open the file in "a+" mode
f1 = open("file_5.txt", "a+")

# Append content to the file
f1.write("This is appended content\n")

# Move the cursor to the beginning of the file
f1.seek(0)

# Read and print the file's content
print(f1.read())

# Close the file
f1.close()
            
        

Writing to a File

  • To write to a file, we first need to open it in write or append mode, depending on whether we want to overwrite existing content or add new content at the end of the file.
  • If we open an existing file in write mode, the previous data will be erased, and the file object will be positioned at the beginning of the file.
  • On the other hand, in append mode, new data will be added at the end of the previous data, as the file object is positioned at the end of the file.
  • After opening the file, we can use the following methods to write data into the file:
    1. write(): The write method takes a string as an argument and writes it to the text file. It returns the number of characters being written on a single execution of the write function.
    2. writelines(): This method is used to write multiple lines of text to the file by passing a list of strings as an argument.

write() method

  • The write method takes a string as an argument and writes it to the text file. It returns the number of characters being written on a single execution of the write function.
  • We can also add a newline character "\n" at the end of every sentence to mark the end of a line.

Example:

        
f1 = open("f1.txt", "w")
f1.write("Hi, this is the line that I'm writing\n")
        
    
  • We need to convert numbers to strings before writing them to a file because the write method only accepts strings. Attempting to write a number directly will result in a TypeError.
  • Example:

                
    num = 123
    f1.write(str(num))
                
            
  • The write function actually writes data to a buffer. When the close function is executed, the contents from this buffer are moved to the file located on permanent storage.

writelines() Method

  • The writelines() method is used to write multiple strings to a file. We need to pass an iterable object containing strings to the writelines() function.
  • Unlike the write() function, the writelines() function does not return the number of characters written in the file.
  • It is useful when we have a list of strings that we want to write to a file without manually looping through each string and using the write() function for each one.
  • Each string in the iterable object passed to writelines() is written to the file as a separate line.
  • This method is commonly used when writing data from a list or other iterable data structure to a text file, such as writing multiple lines of text or data records.

Example:

                        
# Open a file in write mode
f2 = open("f2.txt", "w")

# List of strings to write to the file
str_list = ["Hi", "Hello"]

# Write the list of strings to the file using writelines()
f2.writelines(str_list)

# Close the file after writing
f2.close()
                        
                    

Reading from a Text File

  • To read the contents of a file, we need to ensure that the file is opened in one of the modes: "r" (read), "r+" (read and write), "w+" (write and read), or "a+" (append and read).
  • There are three methods to read content from a file:
    1. read(): Reads a specified number of bytes of data from a file.
    2. readline(): Reads one complete line from a file, terminating at the new line character ("\n").
    3. readlines(): Reads all lines from a file and returns them as a list of strings, each line ending with a new line character.

read() Method:

  • This method is used to read a specified number of bytes of data from a file.
  • If no argument or a negative number is specified in the read() function, the entire file content is read.

Example:

                        
f1 = open("abc.txt", "r") #make sure this file exists and there is data inside it.
# Reading the entire file
content = f1.read()
print("Content of the file:")
print(content)

# Resetting the file pointer to the beginning
f1.seek(0)

# Reading the first 10 characters
content = f1.read(10)
print("\nFirst 10 characters of the file:")
print(content)
                
                    

Explanation:

  • f1.read(): Reads the entire content of the file example.txt and prints it.
  • f1.seek(0): Resets the file pointer to the beginning of the file.
  • f1.read(10): Reads the first 10 characters from the file example.txt and prints them.
  • The file pointer moves forward by the number of characters read, so subsequent reads continue from the current position of the file pointer.
  • If you attempt to read more characters than are left in the file, read will return fewer characters than requested, or an empty string if the file pointer is already at the end of the file.

readline() Method:

  • This method reads one complete line from a file, terminating at the new line character ("\n").
  • If no arguments or a negative number is specified, it reads a complete line and returns the string.

Example:

        
f2 = open("myfile.txt", "r")
line = f2.readline()  # Reads one line from the file
print(line)  # Output: First line of myfile.txt
        
    

Explanation:

  • The open() function is used to open the file "myfile.txt" in read mode ("r").
  • The readline() method is then applied to read one complete line from the file and store it in the variable line.
  • The print() function is used to display the content of line, which represents the first line of the file.

readlines() Method:

  • This method reads all the lines from a file and returns them as a list of strings, each line ending with a new line character.
  • When we read a file using the readlines() function, each line in the file becomes an element of the list, where each list element ends with a new character.

Example:

        
f2 = open("myfile.txt", "r")
lines = f2.readlines()  # Reads all lines from the file
print(lines)  # Output: List of lines from myfile.txt
        
    

Explanation:

  • The open() function is used to open the file "myfile.txt" in read mode ("r").
  • The readlines() method is then applied to read all lines from the file and store them in the variable lines.
  • The print() function is used to display the content of lines, which represents a list of lines from the file.

Using the "with" Clause in File Handling

  • The "with" clause is used in Python for file handling to ensure proper handling of resources.
  • It automatically closes the file after the block of code inside the "with" statement is executed, even if an exception occurs.
  • This helps in avoiding common issues like forgetting to close the file, leading to resource leaks.

Example code:

                    
with open('example.txt', 'r') as file:
    data = file.read()
    # Perform operations on the file
# File automatically closed outside the "with" block
                    
                

Reference