0% found this document useful (0 votes)
5 views28 pages

Module 3 - Python

This document provides an overview of Python dictionaries, detailing their structure as key:value pairs, differences from sequences, and methods for creating and manipulating them. It covers operations such as adding, updating, deleting elements, and iterating through dictionaries, as well as the concepts of aliasing and copying. Additionally, it introduces the NumPy library for mathematical operations, highlighting its advantages over standard Python data types.

Uploaded by

anushafernandes
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views28 pages

Module 3 - Python

This document provides an overview of Python dictionaries, detailing their structure as key:value pairs, differences from sequences, and methods for creating and manipulating them. It covers operations such as adding, updating, deleting elements, and iterating through dictionaries, as well as the concepts of aliasing and copying. Additionally, it introduces the NumPy library for mathematical operations, highlighting its advantages over standard Python data types.

Uploaded by

anushafernandes
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python notes

Module 3

5.4 Dictionaries

A dictionary is a compound data type in Python that stores data as key : value pairs.
It is Python’s built-in mapping type, unlike sequences such as strings, lists, and tuples which use indices.

• Keys → must be immutable (e.g., int, float, string, tuple)


• Values → can be any data type (heterogeneous)
• Dictionaries are also called associative arrays

Difference Between Sequences and Dictionaries

Feature Sequences (List/Tuple/String) Dictionary


Access method Index (0, 1, 2, …) Key
Order Ordered Unordered
Indexing Allowed Not allowed
Slicing Allowed Not allowed

Creating a Dictionary

1. Creating an Empty Dictionary and Adding Elements

english_spanish = {}
english_spanish["one"] = "uno"
english_spanish["two"] = "dos"

Output:

{'two': 'dos', 'one': 'uno'}

Note: Order of elements may vary due to hashing.

2. Creating a Dictionary with Initial Values

english_spanish = {
"one": "uno",
"two": "dos",
"three": "tres"
}

3. Dictionary with Different Data Types

student = {
"name": "Anusha",
"age": 20,
"marks": [85, 90, 88],
"passed": True
}

Accessing Values in a Dictionary

Values are accessed using keys, not indices.

1 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

print(english_spanish["two"])

Output:

dos

Invalid:

english_spanish[0] # Error

Hashing (Why Dictionaries Are Fast)

• Dictionaries use a technique called hashing


• Each key is converted into a hash value
• This allows constant-time access (O(1))
• Order of elements is unpredictable

Dictionary vs List of Tuples

Dictionary:

prices = {"apples": 430, "bananas": 312}

List of tuples:

prices = [("apples", 430), ("bananas", 312)]


Feature Dictionary List of Tuples
Access speed Very fast Slow

Search Direct by key Linear search

Implementation Hash table Sequential

Reason: Dictionary does not require searching through all elements.

Common Dictionary Operations

1. Adding / Updating Elements

english_spanish["four"] = "cuatro"
english_spanish["one"] = "UNO" # Updates value

2. Deleting Elements

del english_spanish["three"]

3. Checking if a Key Exists

"two" in english_spanish

Output:

True

2 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

4. Length of Dictionary

len(english_spanish)

Iterating Through a Dictionary

Iterating Over Keys Iterating Over Values Iterating Over Key–Value Pairs

for key in english_spanish: for value in english_spanish.values(): for key, value in english_spanish.items():
print(key) print(value) print(key, ":", value)

Important Characteristics

• Dictionaries are mutable


• Keys must be unique
• Keys must be immutable
• Values can be duplicate
• Dictionaries are not sequences

Real-World Examples

Example 1: Student Marks

marks = {
"Maths": 90,
"Physics": 85,
"Chemistry": 88
}

Example 2: Phone Directory

phone_book = {
"Anusha": 9876543210,
"Rahul": 9123456780
}

5.4.1 Dictionary Operations

Dictionaries support operations to add, delete, update, and inspect key:value pairs.

a. Deleting Elements using del

The del statement removes a key:value pair from a dictionary.

Example 1:

inventory = {"apples": 430, "bananas": 312, "oranges": 525, "pears": 217}


print(inventory)

Output:

{'pears': 217, 'apples': 430, 'oranges': 525, 'bananas': 312}

3 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

Removing bananas:

del inventory["bananas"]
print(inventory)

Output:

{'apples': 430, 'oranges': 525, 'pears': 217}

Example 2:
student = {"name": "Ravi", "age": 21, "course": "AI"}
del student["age"]
print(student)

Output:

{'name': 'Ravi', 'course': 'AI'}

Important:
Accessing a deleted or non-existent key causes a KeyError.

inventory["bananas"] # KeyError

b. Adding a New Entry

If the key does not exist, assignment creates a new key:value pair.

Example 1:
inventory["bananas"] = 0
print(inventory)

Output:

{'pears': 217, 'apples': 430, 'oranges': 525, 'bananas': 0}

Example 2:
employee = {}
employee["id"] = 101
employee["department"] = "HR"
print(employee)

Output:

{'id': 101, 'department': 'HR'}

c. Modifying an Existing Value

If the key already exists, assignment updates the value.

Example 1: New shipment arrives

inventory["bananas"] += 200
print(inventory)

Output:

{'pears': 217, 'apples': 430, 'oranges': 525, 'bananas': 200}

4 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

This shows that dictionaries are mutable.

Example 2:

marks = {"Maths": 80, "Physics": 75}

marks["Maths"] = marks["Maths"] + 10

print(marks)

Output:

{'Maths': 90, 'Physics': 75}

d. Using len() with Dictionaries

The len() function returns the number of key:value pairs.

Example 1:
len(inventory)

Output:4

Example 2:
books = {"Python": 3, "AI": 5, "ML": 2}
print(len(books))

Output:3

5.4.2 Dictionary Methods

Python dictionaries provide several built-in methods to work efficiently with keys and values.

a. keys() Method

Returns a view object containing all keys.


A view is lazy, meaning values are produced only when needed.

Example 1:

for key in english_spanish.keys():


print("Got key", key, "which maps to value", english_spanish[key])

Output (order not guaranteed):

Got key three which maps to value tres


Got key two which maps to value dos
Got key one which maps to value uno

Converting keys to a list:

keys = list(english_spanish.keys())
print(keys)

5 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

Example 2:
country_codes = {"India": 91, "USA": 1, "UK": 44}
for key in country_codes.keys():
print(key)

Output:
India
USA
UK

b. Iterating Directly over a Dictionary

Iterating over a dictionary automatically iterates over its keys.

Example 1:
for key in english_spanish:
print("Got key", key)

Example 2:
for subject in {"Maths": 90, "Physics": 85}:
print(subject)

c. values() Method

Returns a view object containing all values.

Example 1:
list(english_spanish.values())

Output:

['tres', 'dos', 'uno']

Example 2:
scores = {"A": 90, "B": 80, "C": 70}
print(list([Link]()))

Output:

[90, 80, 70]

d. items() Method

Returns a view of (key, value) tuples.

Example 1:
list(english_spanish.items())

Output:

[('three', 'tres'), ('two', 'dos'), ('one', 'uno')]

Example 2:
prices = {"Pen": 10, "Book": 50}
for item, price in [Link]():
print(item, "costs", price)

6 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

Output:

Pen costs 10
Book costs 50

e. Looping Using items()

Useful when both key and value are required.

for (key, value) in english_spanish.items():


print("Got", key, "that maps to", value)

Output:

Got three that maps to tres


Got two that maps to dos
Got one that maps to uno

f. Membership Operators: in and not in

Used to check whether a key exists in a dictionary.

Example 1:
"one" in english_spanish

Output:

True
"six" in english_spanish

Output:

False

Example 2:

users = {"admin": "Anu", "guest": "Sam"}


print("admin" in users)
print("manager" not in users)

Output:
True
True

Important:
in checks keys, not values.

"tres" in english_spanish

Output:False

Avoiding KeyError

Looking up a non-existent key causes a runtime error.

english_spanish["dog"]

7 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

Error:

KeyError: 'dog'

Safer approach:

Example 1:

if "dog" in english_spanish:
print(english_spanish["dog"])

Example 2:
data = {"temp": 30}

if "humidity" in data:

print(data["humidity"])

else:

print("Key not found")

Output:Key not found

5.4.3 Aliasing and Copying (Dictionaries)

Aliasing

Aliasing occurs when two or more variables refer to the same dictionary object in memory.
Since dictionaries are mutable, a change made through one variable is reflected in all aliases.

Example 1: Aliasing in Dictionaries

opposites = {"up": "down", "right": "wrong", "yes": "no"}

alias = opposites

Here:

• alias and opposites refer to the same dictionary

Modifying alias:

alias["right"] = "left"

print(opposites["right"])

Output:left

Explanation:
Because both names point to the same object, the change is visible through opposites.

Example 2: Aliasing with Student Records

student1 = {"name": "Anu", "marks": 85}

student2 = student1

student2["marks"] = 95

print(student1)

8 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

Output:

{'name': 'Anu', 'marks': 95}

Change in student2 affects student1.

Copying a Dictionary

Why Copying is Needed

If we want to modify a dictionary without changing the original, we must create a copy.

Python provides the copy() method, which creates a shallow copy.

Shallow Copy using copy()

opposites = {"up": "down", "right": "wrong", "yes": "no"}

copy_dict = [Link]()

• copy_dict is a new dictionary

• It contains the same key:value pairs

Example 1: Copy Does Not Affect Original

copy_dict["right"] = "privilege"

print(opposites["right"])

Output:

wrong

Explanation:Changes made to copy_dict do not affect opposites.

Example 2: Copying Inventory Data

inventory = {"apples": 50, "oranges": 30}

backup = [Link]()

backup["apples"] = 0

print(inventory)

Output:

{'apples': 50, 'oranges': 30}

Original dictionary remains unchanged.

Comparison: Aliasing vs Copying

Feature Aliasing Copying

Memory Same object New object

Change effect Affects all references Affects only copy

Method used Assignment (=) copy()

9 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

Feature Aliasing Copying

Safety Unsafe for backups Safe for backups

5.4.4 Counting Letters (Frequency Table using Dictionary)

Counting how many times each letter appears in a string is called creating a frequency table.
A dictionary is ideal for this task because it maps each letter (key) to its count (value).

Why Frequency Tables Are Useful

• Text compression (shorter codes for frequent letters)

• Text analysis

• Pattern recognition

• Cryptography and data processing

Basic Idea

• Start with an empty dictionary

• Traverse each character in the string

• Increase its count if it already exists

• Otherwise, start its count at 0

Example 1: Counting Letters in a Word

letter_counts = {}

for letter in "Mississippi":

letter_counts[letter] = letter_counts.get(letter, 0) + 1

print(letter_counts)

Output:

{'M': 1, 's': 4, 'p': 2, 'i': 4}

Explanation

• get(letter, 0)

o Returns the current count of the letter

o Returns 0 if the letter is not present

• + 1 increments the count

Example 2: Counting Letters in a Sentence

text = "hello world"

10 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

counts = {}

for ch in text:
if ch != " ":
counts[ch] = [Link](ch, 0) + 1

print(counts)

Output:

{'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}

NumPy

Why NumPy is Needed


The standard Python data types (lists, tuples) are not suitable for mathematical operations.
Python lists are designed to store collections of items, not as mathematical vectors or matrices.

Operation Code Output / Result Limitation


Multiplying list by a = [2, 3, 8] Performs repetition, not arithmetic
[2, 3, 8, 2, 3, 8]
integer 2*a multiplication
Multiplying list by
2.1 * a TypeError Lists do not support float multiplication
float
values = [2, 3, 8]
result = []
Manual loop-based Not elegant Slow for large data
for x in values: [4.2, 6.3, 16.8]
multiplication Not mathematically intuitive
[Link](2.1 * x)
print(result)

Introduction to NumPy

Feature Description
NumPy Numerical Python library
Purpose Supports mathematical array and matrix operations
Core Object ndarray (NumPy array)

Creating a NumPy Array

Example Code
import numpy as np
Example 1
a = [Link]([2, 3, 8])
Example 2 b = [Link]([1, 4, 6])

numpy is conventionally imported as np

Scalar Multiplication with NumPy Arrays

Example Code Output


Example 1 2.1 * a array([4.2, 6.3, 16.8])
Example 2 3 * b array([3, 12, 18])

Observations:

11 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

• Element-wise operation
• Automatic type conversion
• No loops required

Element-Wise Array Multiplication

Example Code Output


Example 1 a * a array([4, 9, 64])
Example 2 b * b array([1, 16, 36])

Power Operator (**)

Example Code Output


Example 1 a ** 2 array([4, 9, 64])
Example 2 b ** 3 array([1, 64, 216])

Operations are element-wise, not vector algebra.

Element-Wise Addition

Example Code Output


Example 1 x+y array([5, 7, 9])
Example 2 a+b array([3, 7, 14])

Dot Product ([Link]())

Example Code Output


Example 1 [Link](a, a) 77
Example 2 [Link](x, y) 32

Dot product = algebraic vector multiplication

Matrix Multiplication using [Link]()

Example Code Output


Example 1 [Link](A, B) [[19, 22], [43, 50]]
Example 2 [Link](B, A) [[23, 34], [31, 46]]

Other Useful NumPy Algebra Functions

Function Purpose
[Link]() Dot product / Matrix multiplication
[Link]() Cross product
[Link]() Outer product
[Link]() Matrix transpose

Cross Product ([Link]())

12 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

Example Code Output


Example 1 [Link]([1,0,0],[0,1,0]) [0, 0, 1]
Example 2 [Link]([0,1,0],[0,0,1]) [1, 0, 0]

6.1 Shape (NumPy Arrays)

The shape of a NumPy array describes the number of elements along each dimension.
It tells us whether an array is 1D, 2D, 3D, etc.

Why Shape Is Important

• Helps understand array structure

• Required for matrix operations

• Used in image and signal processing

Example:

• Grayscale image → 2D array

• Color image (RGB) → 3D array

Finding the Shape of an Array

• Use the shape attribute.

1D Array Shape

Code Output Meaning


import numpy as np
a = [Link]([2, 3, 8]) (3,) 1D array with 3 elements
[Link]

The comma indicates it is one-dimensional.

2D Array Shape

Code Output Meaning


b = [Link]([[2, 3, 8],[4, 5, 6]])
(2, 3) 2 rows × 3 columns
[Link]

Array Type Shape Format Example

1D (n,) (3,)

2D (rows, cols) (2,3)

3D (x, y, z) (100,100,3)

13 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

6.2 Slicing (NumPy Arrays)

Slicing is used to select specific elements, rows, or columns from a NumPy array.
For 1D arrays, slicing works like Python lists.

For 2D arrays, slicing can be done along rows and columns.

• Slicing in 1D Arrays

import numpy as np

a = [Link]([2, 3, 8])

Operation Code Output

Access element a[2] 8

Slice from index 1 a[1:] array([3, 8])

Indexing starts from 0.

• Slicing in 2D Arrays

b = [Link]([[2, 3, 8],

[4, 5, 6]])

• Accessing Rows

Operation Code Output

Get 1st row b[1] array([4, 5, 6])

Accessing Individual Elements

Operation Code Output

Using two steps b[1][2] 6

Using single index b[1,2] 6

b[row, column] is the preferred format.

• Accessing Columns

Operation Code Output

Get 1st column b[:,1] array([3, 5])

: selects all rows, 1 selects column index 1.

Examples

Selecting All Rows, Specific Column

14 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

Code Output

b[:,0] array([2, 4])

Selecting Specific Row, All Columns

Code Output

b[0,:] array([2, 3, 8])

Sub-matrix Selection

Code Output

b[:, 1:3] array([[3, 8], [5, 6]])

Summary Table

Syntax Meaning

a[i] Element of 1D array

b[i] i-th row

b[i,j] Element at row i, column j

b[:,j] j-th column

b[i,:] i-th row (explicit)

6.4 Broadcasting (NumPy)

Definition

Broadcasting allows NumPy to perform element-wise operations on arrays of different shapes by


automatically expanding (stretching) dimensions of size 1.

Basic Broadcasting Example

import numpy as np

a = [Link]([[0, 1],

[2, 3],

[4, 5]])

15 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

b = [Link]([10, 100])

a*b

Output

array([[ 0, 100],

[ 20, 300],

[ 40, 500]])

Explanation

• [Link] = (3, 2)

• [Link] = (2,) → treated as (1, 2)

• (1, 2) is stretched to (3, 2)

• Operation is element-wise

Broadcasting Rules (Exam Important)

Rule Explanation

Rule 1 Only dimensions of size 1 can be stretched

Rule 2 Comparison starts from the last dimension

Rule 3 Dimensions must be equal or one must be 1

Shape Transformation in Broadcasting

Array Original Shape After Broadcasting

a (3, 2) (3, 2)

b (2,) (1, 2) → (3, 2)

Example Where Broadcasting Fails

c = [Link]([[0, 1, 2],

[3, 4, 5]])

b = [Link]([10, 100])

c*b

16 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

Error

ValueError: operands could not be broadcast together with shapes (2,3) (2,)

Reason

Dimension c B

Last 3 2

Stretchable? No No

Neither dimension is 1, so broadcasting fails.

Fixing Broadcasting Using None (or [Link])

c = [Link]([[0, 1, 2],

[3, 4, 5]])

b = [Link]([10, 100])

c * b[:, None]

Output

array([[ 0, 10, 20],

[300, 400, 500]])

6.5 dtype

dtype specifies the type and size of data stored in a NumPy array (e.g., int8, uint8, int32, float64).

Unlike Python, NumPy uses fixed-size data types.

Common Integer Data Types

dtype Bits Range

uint8 8 0 to 255

int8 8 −128 to 127

uint16 16 0 to 65,535

int16 16 −32,768 to 32,767

int64 64 −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

u → unsigned (no negatives)

Example 1: Checking dtype

import numpy as np

a = [Link]([1, 2, 3])

17 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

[Link]

Output

dtype('int64')

Example 2: Setting dtype Explicitly

a = [Link]([1, 2, 3], dtype='uint8')

[Link]

Output

dtype('uint8')

Overflow Problem in NumPy

Example: Overflow with uint8

a = [Link]([200], dtype='uint8')

a+a

Output

array([144], dtype=uint8)

Explanation

Calculation Result

Expected 200 + 200 = 400

Max uint8 255

Actual stored 400 − 256 = 144

NumPy does not auto-expand data types.

Fixing Overflow Using Larger dtype

a = [Link]([200], dtype='uint16')

a+a

Output

array([400], dtype=uint16)

Memory vs Precision Trade-off

Dtype Memory Usage Overflow Risk

Smaller (uint8) Low High

Larger (uint16, int64) High Low

Use small dtype only when value range is known.

18 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

Real-World Example: Images

• Image pixels stored as RGB tuples

• Each channel uses uint8

• Range: 0–255

Color RGB

Black (0, 0, 0)

Red (255, 0, 0)

Problem Example

image + image

Causes overflow, resulting in noise, not brightness.

Always convert image dtype before arithmetic:

[Link]('uint16')

6.6 Changing dtype

To change the dtype of an existing array, you can use the as type method:

import numpy as np

a = [Link]([200], dtype='uint8')

[Link]('uint64')

7.1 About Files

File Storage:

• During program execution, data is stored in RAM.

• RAM is volatile → data is lost when the program ends or power is off.

• To store data permanently, it must be saved in non-volatile storage.

Volatile vs Non-Volatile Memory

Memory Type Example Data Retention

Volatile RAM Data lost on shutdown

Non-Volatile Hard disk, USB, CD-RW Data preserved permanently

File:

• A file is a named location on non-volatile storage.

• Used to store data permanently.

• Allows programs to save and retrieve data between executions.

19 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

Why Files are Needed

• Preserve program data

• Store logs, reports, images, databases

• Share data between programs

File–Notebook Analogy

Notebook File

Must be opened File must be opened

Can be read or written File can be read or written

Has a position (page) Has a file pointer

Must be closed File must be closed

Basic File Operations

Operation Description

Open Access file by name and mode

Read Retrieve data from file

Write Store data into file

Close Release file resources

File Access Modes

Mode Purpose

r Read

w Write (overwrite)

a Append

7.2 Writing Our First File

Example Program (Writing to a File)

with open("[Link]", "w") as myfile:

[Link]("My first file written from Python\n")

[Link]("---------------------------------\n")

[Link]("Hello, world!\n")

Explanation

1. open() Function

20 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

• open(filename, mode) opens a file and returns a file handle.

• "[Link]" → name of the file

• "w" → write mode

File Handle

• myfile is a file handle.

• It represents the opened file in the program.

• Methods like write() operate on this handle to modify the actual file on disk.

Write Mode ("w")

Situation Result

File does not exist New file is created

File already exists Existing file is overwritten

Writing Data to File

• write() method is used to write text.

• \n is used to move to a new line.

• Multiple write() calls add multiple lines.

• In large programs, writing is usually done using loops.

with Statement

• Automatically closes the file after use.

• Ensures file closure even if an error occurs.

• Eliminates the need to explicitly call close().

Advantages of Using with

✔ File is safely closed

✔ Prevents data loss

✔ Cleaner and safer code

7.3 Reading a File Line-at-a-Time

Example Program

with open("[Link]", "r") as my_new_handle:

for the_line in my_new_handle:

print(the_line, end="")

Explanation

Opening a File for Reading

21 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

• Mode "r" → opens the file in read mode

• The file must already exist, otherwise an error occurs

Reading Line by Line

• The for loop reads the file one line at a time

• Each iteration assigns one complete line (including \n) to the_line

• Efficient for large files (no need to load entire file into memory)

Why end="" in print()?

• Each line already ends with a newline (\n)

• print() adds another newline by default

• Using end="" prevents extra blank lines

Common Use Cases

• Processing files with many lines

• Reading names, emails, marks, logs, etc.

• Applying logic to each line (splitting, searching, counting)

Example: Processing Each Line

with open("[Link]", "r") as file:

for line in file:

name, email = [Link](",")

print(name, email)

File Not Found Error

open("[Link]", "r")

Error:

FileNotFoundError: [Errno 2] No such file or directory

Reason:

• File does not exist

• File name or path is incorrect

7.4 Turning a File into a List of Lines

Purpose

• Convert file contents into a list of lines

• Enables easy processing like sorting, searching, filtering, etc.

Example: Reading, Sorting, and Writing Lines

with open("[Link]", "r") as input_file:

22 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

all_lines = input_file.readlines()

all_lines.sort()

with open("[Link]", "w") as output_file:

for line in all_lines:

output_file.write(line)

Explanation

readlines() Method

• Reads entire file at once

• Returns a list of strings

• Each string ends with a newline (\n)

Example:

["Alice,alice@[Link]\n", "Bob,bob@[Link]\n"]

Sorting Lines

• sort() arranges lines lexicographically (alphabetical order)

• Sorting is done in memory on the list

Writing Back to a File

• Open file in "w" mode

• Write each line using a loop

• Preserves newline characters

Why Use readlines()?

✔ Simple and clean

✔ Less code

✔ Ideal for small–medium sized files

⚠ Not suitable for very large files (high memory usage)

Alternative Approach (Manual Loop)

lines = []

with open("[Link]", "r") as f:

for line in f:

[Link](line)

➡ Works, but readlines() is easier.

23 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

7.5 Reading the Whole File at Once

• Read the entire contents of a file into a single string

• Useful when line structure is not important

Example: Counting Words in a File

with open("[Link]") as f:

content = [Link]()

words = [Link]()

print("There are {0} words in the file.".format(len(words)))

Explanation

read() Method

• Reads entire file content at once

• Stores data as one string

• Includes spaces and newline characters

String Processing

• split() breaks the string into a list of words

• Default split is based on whitespace

• len(words) gives total word count

File Mode

• Mode "r" is optional

• If mode is not specified, Python opens the file in read mode by default

When to Use This Method

✔ Word counting

✔ Pattern matching

✔ Text analysis

✔ File content replacement

⚠ Not suitable for very large files (high memory usage)

File Paths

Same Directory

open("[Link]")

Absolute Paths

• Windows:

"C:\\temp\\[Link]"

24 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

• Linux / Unix:

"/home/jimmy/[Link]"

7.6 An Example – File Filter

What is a Filter?

• A filter is a program that:

o Reads a file line by line

o Processes each line

o Writes selected or modified lines to another file

Example: Removing Comment Lines

Program

def filter(oldfile, newfile):

with open(oldfile, "r") as infile, open(newfile, "w") as outfile:

for line in infile:

if not [Link]('#'):

[Link](line)

Explanation

Opening Two Files

• oldfile → opened in read mode

• newfile → opened in write mode

• Both files are safely handled using a single with statement

Line-by-Line Processing

• Input file is read one line at a time

• Efficient and suitable for large files

Filtering Logic

• startswith('#') checks for comment lines

• Lines beginning with # are skipped

• All other lines are written to the output file

Example Input ([Link])

# This is a comment

name,marks

Anu,85

# End of file

25 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

Output ([Link])

name,marks

Anu,85

7.7 Directories

File System

• A file system organizes data on storage devices

• Consists of:

o Files – store data

o Directories (folders) – contain files and subdirectories

Current Directory

• Files created using open() are stored in the current directory

• When reading a file, Python searches the current directory by default

File Paths

• To access a file in another directory, a path must be specified

Example (Unix/Linux)

wordsfile = open("/usr/share/dict/words", "r")

wordlist = [Link]()

print(wordlist[:6])

• / → root directory

• Path shows the hierarchy of directories

Windows File Paths

"c:/temp/[Link]"

"c:\\temp\\[Link]"

Double backslash (\\) is required because \ is an escape character in strings.

Path Rules

• / and \ cannot be used in file names

• They are reserved as directory separators

Using [Link]

Why use [Link]?

✔ Handles OS-specific path separators

✔ Avoids escape character issues

✔ Improves code portability

26 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

Example

import os

filepath = [Link]("directory", "[Link]")

• Unix/Linux → directory/[Link]

• Windows → directory\[Link]

Advantages of [Link]

• Platform-independent file handling

• Cleaner and safer code

• Easier collaboration and code sharing

7.8 Fetching Data from the Web

Python can download data from the internet and either save it to a file or process it directly in memory.

Method 1: Using [Link] (Standard Library)

Example: Download Web Content to a File

import [Link]

url = "[Link]

destination_filename = "[Link]"

[Link](url, destination_filename)

Explanation

• urlretrieve() downloads the content at the URL

• Saves it directly to a local file

• File is created in the current directory

Requirements for urlretrieve()

✔ URL must exist

✔ Write permission to destination file

✔ Internet connection

✔ Proxy settings (if applicable)

Safety Considerations

• Web content may change or disappear

• Always verify downloaded data

• Never blindly execute or display fetched content

27 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga
Python notes

Method 2: Using requests Module (Recommended)

requests is not part of the standard library, but easier and more powerful.

Example: Reading Web Content into a String

import requests

url = "[Link]

response = [Link](url)

print([Link])

Explanation

• get() sends an HTTP request

• [Link] contains the entire content as a string

Reading Web Content Line by Line

import requests

url = "[Link]

response = [Link](url)

for line in response:

print(line)

Comparison: urllib vs requests

Feature urllib Requests

Library type Standard External

Ease of use Moderate Very easy

Power Limited High

Read as string Indirect Direct ([Link])

28 By,

Anusha Prima Fernandes, Asst. Professor, JNNCE


Shivamogga

You might also like