0% found this document useful (0 votes)
8 views23 pages

Python Module-3 Study Material

This document covers Python dictionaries, detailing their structure as key-value pairs and operations such as adding, removing, and modifying entries. It also introduces NumPy, highlighting its advantages over Python lists for numerical computations, including array operations and shape management. Key features of dictionaries and NumPy, including methods and functionalities, are discussed with examples.

Uploaded by

darshanking2303
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)
8 views23 pages

Python Module-3 Study Material

This document covers Python dictionaries, detailing their structure as key-value pairs and operations such as adding, removing, and modifying entries. It also introduces NumPy, highlighting its advantages over Python lists for numerical computations, including array operations and shape management. Key features of dictionaries and NumPy, including methods and functionalities, are discussed with examples.

Uploaded by

darshanking2303
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 PROGRAMMING-1BPLC105B MODULE-3

MODULE -3
[Link]
All of the compound data types we have studied in detail so far — strings, lists, and tuples — are sequence
types, which use integers as indices to access the values they contain within them.

Dictionaries are yet another kind of compound type. They are Python’s built-in mapping type. They
map keys, which can be any immutable type, to values, which can be any type (heterogeneous), just like
the elements of a list or tuple. In other programming languages, they are called associative arrays since
they associate a key with a value.

As an example, we will create a dictionary to translate English words into Spanish. For this dictionary, the
keys are strings.

One way to create a dictionary is to start with the empty dictionary and add key:value pairs. The empty
dictionary is denoted {}:

eng2sp = {}

eng2sp["one"] = "uno"

eng2sp["two"] = "dos"

The first assignment creates a dictionary named eng2sp; the other assignments add new key:value pairs to
the dictionary. We can print the current value of the dictionary in the usual way:

eng2sp = {}

eng2sp["one"] = "uno"

eng2sp["two"] = "dos"

print(eng2sp)

>>> =================== OUTPUT ===================

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

The key:value pairs of the dictionary are separated by commas. Each pair contains a key and a value
separated by a colon.

Another way to create a dictionary is to provide a list of key:value pairs using the same syntax as the
previous output:

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

print(eng2sp)

>> =================== OUTPUT ===================

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


1
PYTHON PROGRAMMING-1BPLC105B MODULE-3

It doesn’t matter what order we write the pairs. The values in a dictionary are accessed with keys, not with
indices, so there is no need to care about ordering.

Here is how we use a key to look up the corresponding value:

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

print(eng2sp["two"])

>>> =================== OUTPUT ===================

dos

The key "two" yields the value "dos".

Lists, tuples, and strings have been called sequences, because their items occur in order. The dictionary is
the first compound type that we’ve seen that is not a sequence, so we can’t index or slice a dictionary.

1.1Dictionary operations

The del statement removes a key:value pair from a dictionary. For example, the following dictionary
contains the names of various fruits and the number of each fruit in stock:

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

print(inventory)

>>> =================== OUTPUT ===================

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

If someone buys all of the pears, we can remove the entry from the dictionary:

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

print(inventory)

del inventory["pears"]

print(inventory) # now there are no pears

>>> =================== OUTPUT ===================

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

2
PYTHON PROGRAMMING-1BPLC105B MODULE-3
{'apples': 430, 'bananas': 312, 'oranges': 525}

Or if we’re expecting more pears soon, we might just change the value associated with pears:

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

print(inventory)

inventory["pears"] = 0

print(inventory) # now there are 0 pears

>> =================== OUTPUT ===================

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

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

A new shipment of bananas arriving could be handled like this:

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

print(inventory)

inventory["bananas"] += 200

print(inventory) # now there are more bananas

>>> =================== OUTPUT ===================

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

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

The len function also works on dictionaries; it returns the number of key:value pairs:

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

print(len(inventory))

>>> =================== OUTPUT ===================

1.2. Dictionary methods

Dictionaries have a number of useful built-in methods.

3
PYTHON PROGRAMMING-1BPLC105B MODULE-3
The keys method returns what Python 3 calls a view of its underlying keys. A view object has some
similarities to the range object we saw earlier — it is a lazy promise, to deliver its elements when they’re
needed by the rest of the program. We can iterate over the view, or turn the view into a list like this:

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

for k in [Link](): # The order of the k's is not defined

print("Got key "+str(k)+" which maps to value "+str(eng2sp[k]))

ks = list([Link]())

print(ks)

>>> =================== OUTPUT ===================

Got key one which maps to value uno

Got key two which maps to value dos

Got key three which maps to value tres

['one', 'two', 'three']

It is so common to iterate over the keys in a dictionary that we can omit the keys method call in the for loop
— iterating over a dictionary implicitly iterates over its keys:

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

for k in eng2sp: # loop over keys of eng2sp

print("Got key "+str(k)+" which maps to value "+str(eng2sp[k]))

>>> =================== OUTPUT ===================

Got key one which maps to value uno

Got key two which maps to value dos

Got key three which maps to value tres

The values method is similar; it returns a view object which can be turned into a list:

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

print([Link]())

>>> =================== OUTPUT ===================

4
PYTHON PROGRAMMING-1BPLC105B MODULE-3
['uno', 'dos', 'tres']

The items method also returns a view, which promises a list of tuples — one tuple for each key:value pair:

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

print([Link]())

>> =================== OUTPUT ===================

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

Tuples are often useful for getting both the key and the value at the same time while we are looping:

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

for (k,v) in [Link]():

print("Got "+str(k)+" that maps to "+str(v))

>>> =================== OUTPUT ===================

Got one that maps to uno

Got two that maps to dos

Got three that maps to tres

The in and not in operators can test if a key is in the dictionary:

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

print("one" in eng2sp) # should be True

print("six" in eng2sp) # should be False

print("tres" in eng2sp) # should be False -- only looks at keys

>>> =================== OUTPUT ===================

True

False

False

Looking up a non-existent key in a dictionary causes a runtime error:

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

5
PYTHON PROGRAMMING-1BPLC105B MODULE-3
print(eng2sp["dog"]) # will generate an error since "dog" is not a key

Error

KeyError: dog on line 2

Description

This error occurs when a mapping (dictionary) key is not found in the set of existing keys.

To Fix

>>> =================== OUTPUT ===================

We can get around this error by using the get method. This method will return the associated value if the
key is in the dictionary, but we can tell it to return something else if the key is not in the dictionary:

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

print([Link]("three","Not in dictionary!")) # will print three's value

print([Link]("dog","Not in dictionary!")) # will print the message

>>> =================== OUTPUT ===================

tres

Not in dictionary!

1.3. Aliasing and copying

As in the case of lists, because dictionaries are mutable, we need to be aware of aliasing. Whenever two
variables refer to the same object, changes to one affect the other.

If we want to modify a dictionary and keep a copy of the original, use the copy method. For
example, opposites is a dictionary that contains pairs of opposites:

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

alias = opposites

copy = [Link]() # Shallow copy

alias and opposites refer to the same object; copy refers to a fresh copy of the same dictionary. If we
modify alias, opposites is also changed:

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

alias = opposites

alias["right"] = "left"

print(alias)

6
PYTHON PROGRAMMING-1BPLC105B MODULE-3
print(opposites) # changing the alias also changed the original

>>> =================== OUTPUT ===================

{'up': 'down', 'right': 'left', 'yes': 'no'}

{'up': 'down', 'right': 'left', 'yes': 'no'}

If we modify copy, opposites is unchanged:

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

copy = [Link]()

copy["right"] = "left"

print(copy)

print(opposites) # changing the copy did not change the original

>>> =================== OUTPUT ===================

{'up': 'down', 'right': 'left', 'yes': 'no'}

{'up': 'down', 'right': 'wrong', 'yes': 'no'}

1.4. Counting letters

Given a string, we might wish to compute a frequency table of the letters in the string — that is, how many
times each letter appears.

Such a frequency table might be useful for compressing a text file. Because different letters appear with
different frequencies, we can compress a file by using shorter codes for common letters and longer codes
for letters that appear less frequently.

Dictionaries provide an elegant way to generate a frequency table:

letterCounts = {}

for letter in "Mississippi":

letterCounts[letter] = [Link](letter, 0) + 1

print(letterCounts)

>>> =================== OUTPUT ===================

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

We start with an empty dictionary. For each letter in the string, we find the current count (possibly zero)
and increment it. At the end, the dictionary contains pairs of letters and their frequencies.

7
PYTHON PROGRAMMING-1BPLC105B MODULE-3
It might be more appealing to display the frequency table in alphabetical order. We can do that with
the items and sort methods:

letterCounts = {}

for letter in "Mississippi":

letterCounts[letter] = [Link](letter, 0) + 1

letterItems = list([Link]())

[Link]()

print(letterItems)

>>> =================== OUTPUT ===================

[('M', 1), ('i', 4), ('p', 2), ('s', 4)]

Notice in the first line we had to call the type conversion function list. That turns the promise we get
from items into a list, a step that is needed before we can use the list’s sort method.

[Link] (Numerical Python)


2.1Introduction

NumPy stands for Numerical Python. It is one of the most powerful libraries in Python for numerical and
scientific computation.

Key Points

• Provides ndarray (N-dimensional array) — a fast, memory-efficient array.

• Supports vectorized operations (no explicit loops required).

• Used in data science, AI, image processing, machine learning, and scientific research.

• Written in C, making it much faster than Python lists.

Why Use NumPy Instead of Lists?

Python lists are general-purpose containers, not designed for math operations.

Example with Lists

a = [2, 3, 8]

print(2 * a)

8
PYTHON PROGRAMMING-1BPLC105B MODULE-3
Output:

[2, 3, 8, 2, 3, 8]

The list repeats instead of multiplying elements.

print(2.1 * a)

Output:

TypeError: can't multiply sequence by non-int of type 'float'

To achieve multiplication manually:

values = [2, 3, 8]

result = []

for x in values:

[Link](2.1 * x)

print(result)

Output:

[4.2, 6.3, 16.8]

This is slow and inefficient.

Using NumPy Arrays

import numpy as np

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

print(2.1 * a)

Output:

[ 4.2 6.3 16.8]

Key Points

• [Link]() converts a Python list into a NumPy array.

• Operations like +, -, *, /, ** work element-wise.

• NumPy automatically converts data types if needed (e.g., int → float).

• Arrays are homogeneous — all elements have the same data type.

Array Operations

9
PYTHON PROGRAMMING-1BPLC105B MODULE-3
import numpy as np

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

print(a * a)

print(a ** 2)

Output:

[ 4 9 64]

[ 4 9 64]

Dot Product (vector multiplication):

print([Link](a, a))

Output:

77

Key Points

• Arithmetic operations are element-wise.

• Use [Link]() for vector/matrix multiplication.

• Other related operations:

o [Link](a, b) – cross product

o [Link](a, b) – outer product

o [Link](A, B) – matrix multiplication

• Arrays follow broadcasting rules for size mismatch.

2.2 Shape

The shape tells how many elements are along each dimension (rows, columns, etc.).

import numpy as np

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

print([Link])

Output:

(3,)

For 2D arrays:

b = [Link]([

10
PYTHON PROGRAMMING-1BPLC105B MODULE-3
[2, 3, 8],

[4, 5, 6],

])

print([Link])

Output:

(2, 3)

Key Points

• Shape is represented as a tuple (rows, columns, depth, …).

• len([Link]) gives number of dimensions (rank of the array).

• Common functions:

o [Link] → number of dimensions

o [Link] → total number of elements

o [Link]() → change the shape without changing data

2.3 Slicing

Slicing helps in selecting sub-parts of an array.

1D Array

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

print(a[2])

print(a[1:])

Output:

[3 8]

2D Array

b = [Link]([

[2, 3, 8],

[4, 5, 6],

])

print(b[1]) # 2nd row

11
PYTHON PROGRAMMING-1BPLC105B MODULE-3
print(b[1][2]) # Element in row 2, column 3

print(b[1, 2]) # Short form

Output:

[4 5 6]

Selecting a Column

print(b[:, 1])

Output:

[3 5]

Key Points

• : means “take all elements”.

• Indexing starts from 0.

• Advanced slicing allows extraction of rows, columns, or submatrices.

• Negative indices work too (a[-1] = last element).

2.3 Masking

Masking allows conditional filtering and assignment in arrays.

a = [Link]([230, 10, 284, 39, 76])

cutoff = 200

print(a > cutoff)

Output:

[ True False True False False]

Set all values greater than 200 to 0:

a[a > cutoff] = 0

print(a)

Output:

[ 0 10 0 39 76]

Key Points

12
PYTHON PROGRAMMING-1BPLC105B MODULE-3
• a > cutoff creates a Boolean mask.

• Can use operators like <, >=, ==, !=.

• Works well for filtering, cleaning, and thresholding data.

• Used in image processing (e.g., masking pixels).

2.4 Broadcasting

Broadcasting allows operations between arrays of different but compatible shapes.

a = [Link]([

[0, 1],

[2, 3],

[4, 5],

])

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

print(a * b)

Output:

[[ 0 100]

[ 20 300]

[ 40 500]]

If shapes are incompatible:

c = [Link]([

[0, 1, 2],

[3, 4, 5],

])

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

c*b

Output:

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

Fix using None (adds new axis):

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

13
PYTHON PROGRAMMING-1BPLC105B MODULE-3
print(c * b[:, None])

Output:

[[ 0 10 20]

[300 400 500]]

• Broadcasting saves memory — avoids copying arrays.

• Rules:

1. Compare shapes from right to left.

2. Dimensions must match or one must be 1.

• Automatically extends smaller arrays to match shapes.

2.5 dtype (Data Type)

Each NumPy array element has a specific data type, like int8, uint8, float32, etc.

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

print(a + a)

Output:[144]

Overflow occurred (200 + 200 = 400 doesn’t fit in uint8 → wraps around to 144).

Fix by using larger dtype:

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

print(a + a)

Output:[400]

Dtype Description Range

uint8 Unsigned 8-bit integer 0 to 255

int8 Signed 8-bit integer -128 to 127

int64 Signed 64-bit integer -9.22e18 to 9.22e18

• uint8: 0 → 255

• int8: –128 → +127

• Larger dtypes (like int32, int64) store bigger values.

• Image data often uses uint8 (for RGB 0–255).


14
PYTHON PROGRAMMING-1BPLC105B MODULE-3
• Overflow leads to unexpected results (called wrap-around).

• Use appropriate dtype for memory efficiency.

2.6 Changing dtype

To change the dtype of an array:

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

print([Link]('uint64'))

Output:

[200]

Key Points

• .astype(new_dtype) returns a new array with the specified type.

• Common types:

o int32, int64

o float32, float64

o complex64, complex128

• Useful when performing operations that need higher precision or type compatibility.

[Link]
3.1. About files

While a program is running, its data is stored in random access memory (RAM). RAM is fast and
inexpensive, but it is also volatile, which means that when the program ends, or the computer shuts down,
data in RAM disappears. To make data available the next time the computer is turned on and the program
is started, it has to be written to a non-volatile storage medium, such a hard drive, usb drive, or DVD.

Data on non-volatile storage media is stored in named locations on the media called files. By reading and
writing files, programs can save information between program runs.

Working with files is a lot like working with a notebook. To use a notebook, it has to be opened. When
done, it has to be closed. While the notebook is open, it can either be read from or written to. In either
case, the notebook holder knows where they are. They can read the whole notebook in its natural order or
they can skip around.

All of this applies to files as well. To open a file, we specify its name and indicate whether we want to read
or write.

9.2. Writing our first file

Let’s begin with a simple program that writes three lines of text into a file:

15
PYTHON PROGRAMMING-1BPLC105B MODULE-3
myfile = open("[Link]", "w")

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

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

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

[Link]()

Opening a file creates what we call a file handle. In this example, the variable myfile refers to the new
handle object. Our program calls methods on the handle, and this makes changes to the actual file which is
usually located on our disk.

On line 1, the open function takes two arguments. The first is the name of the file, and the second is
the mode. Mode "w" means that we are opening the file for writing.

With mode "w", if there is no file named [Link] on the disk, it will be created. If there already is one, it will
be replaced by the file we are writing.

To put data in the file we invoke the write method on the handle, shown in lines 2, 3 and 4 above. In bigger
programs, lines 2–4 will usually be replaced by a loop that writes many more lines into the file.

Closing the file handle (line 5) tells the system that we are done writing and makes the disk file available for
reading by other programs (or by our own program).

A handle is somewhat like a TV remote control

We’re all familiar with a remote control for a TV. We perform operations on the remote control — switch
channels, change the volume, etc. But the real action happens on the TV. So, by simple analogy, we’d call
the remote control our handle to the underlying TV.

Sometimes we want to emphasize the difference — the file handle is not the same as the file, and the
remote control is not the same as the TV. But at other times we prefer to treat them as a single mental
chunk, or abstraction, and we’ll just say “close the file”, or “flip the TV channel”.

3.3. Reading a file line-at-a-time

Now that the file exists on our disk, we can open it, this time for reading, and read all the lines in the file,
one at a time. This time, the mode argument is "r" for reading:

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

while True: # Keep reading forever

theline = [Link]() # Try to read next line

if len(theline) == 0: # If there are no more lines

break # leave the loop

16
PYTHON PROGRAMMING-1BPLC105B MODULE-3
# Now process the line we've just read

print(theline, end="")

[Link]()

This is a handy pattern for our toolbox. In bigger programs, we’d squeeze more extensive logic into the
body of the loop at line 8 — for example, if each line of the file contained the name and email address of
one of our friends, perhaps we’d split the line into some pieces and call a function to send the friend a
party invitation.

On line 8 we suppress the newline character that print usually appends to our strings. Why? This is because
the string already has its own newline: the readline method in line 3 returns everything up to and
including the newline character. This also explains the end-of-file detection logic: when there are no more
lines to be read from the file, readline returns an empty string — one that does not even have a newline at
the end, hence its length is 0.

Fail first ...

In our sample case here, we have three lines in the file, yet we enter the loop four times. In Python, you
only learn that the file has no more lines by failure to read another line. In some other programming
languages (e.g. Pascal), things are different: there you read three lines, but you have what is called look
ahead — after reading the third line you already know that there are no more lines in the file. You’re not
even allowed to try to read the fourth line.

So the templates for working line-at-a-time in Pascal and Python are subtly different!

When you transfer your Python skills to your next computer language, be sure to ask how you’ll know when
the file has ended: is the style in the language “try, and after you fail you’ll know”, or is it “look ahead”?

You can also use a for loop to read from a file. Each time we execute the loop, the loop variable (theline in
the example below) will be the next line of the file. The for loop will automatically end after the final line of
the file is read.

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

for theline in mynewhandle: # get the next line

# Now process the line we've just read

print(theline, end="")

[Link]()

If we try to open a file that doesn’t exist, we get an error:

>>> mynewhandle = open("[Link]", "r")

IOError: [Errno 2] No such file or directory: "[Link]"


17
PYTHON PROGRAMMING-1BPLC105B MODULE-3
3.4. Turning a file into a list of lines

It is often useful to fetch data from a disk file and turn it into a list of lines. Suppose we have a file
containing our friends and their email addresses, one per line in the file. But we’d like the lines sorted into
alphabetical order. A good plan is to read everything into a list of lines, then sort the list, and then write the
sorted list back to another file:

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

xs = [Link]() # reads the whole file at once into a list

[Link]()

[Link]() # sorts the list

# now write the sorted list to a new file

g = open("[Link]", "w")

for v in xs:

[Link](v)

[Link]()

The readlines method in line 2 reads all the lines and returns a list of the strings.

We could have used the template from the previous section to read each line one-at-a-time, and to build
up the list ourselves, but it is a lot easier to use the method that the Python implementors gave us!

Your file paths may need to be explicitly named.

In the above examples, we’re assuming that the file we’re reading from is in the same directory as your
Python source code. If this is not the case, you may need to provide a full or a relative path to the file. On
Windows, a full path could look like "C:\\temp\\[Link]", while on a Unix system the full path could
be "/home/jimmy/[Link]".

2.5. An example

Many useful line-processing programs will read a text file line-at-a-time and do some minor processing as
they write the lines to an output file. They might number the lines in the output file, or insert extra blank
lines after every 60 lines to make it convenient for printing on sheets of paper, or extract some specific
columns only from each line in the source file, or only print lines that contain a specific substring. We call
this kind of program a filter.

Here is a filter that copies one file to another, omitting any lines that begin with #:

def filter(oldfile, newfile):

# open the files

infile = open(oldfile, "r")

outfile = open(newfile, "w")


18
PYTHON PROGRAMMING-1BPLC105B MODULE-3
# process the files

for text in infile:

if text[0] == "#":

continue # skip any lines that start with "#"

[Link](text) # write any other lines to outfile

# close the files

[Link]()

[Link]()

The continue statement at line 8 skips over the remaining lines in the current iteration of the loop, but the
loop will still iterate.

Let’s consider one more case: suppose our original file contained empty lines. At line 6 above, would this
program find the first empty line in the file, and terminate immediately? No! Recall that readline always
includes the newline character in the string it returns. It is only when we try to read beyond the end of the
file that we get back the empty string of length 0.

3.5 Reading the Whole File at Once

Concept

Instead of reading a file line by line, Python allows reading the entire file into a single string using the read()
method.
This is useful when the structure of the file (like lines) is not important — for example, when performing
text analysis or counting words.

Example

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

content = [Link]()

words = [Link]()

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

("[Link]"): Opens the file for reading (default mode is "r").

• [Link](): Reads the entire file content into a single string.

• split(): Breaks the string into a list of words (default separator is whitespace).

• len(words): Gives the total word count.

19
PYTHON PROGRAMMING-1BPLC105B MODULE-3
• Suitable for small or medium-sized files (large files may consume too much memory).

• Always use the with statement to ensure the file closes automatically.

• File paths:

o On Windows → "C:\\temp\\[Link]"

o On Unix/Linux → "/home/jimmy/[Link]"

• Relative path: File is in the same folder as the Python script.

• Absolute path: Includes the full directory structure.

• If the file is large, consider reading line by line instead.

content = [Link]().lower().split()

to count words in a case-insensitive way.

2.6 An Example – Writing a File Filter

Concept

A filter program reads data from an input file, processes it, and writes the modified data to an output file.

Example

def filter(oldfile, newfile):

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

for line in infile:

if not [Link]('#'):

[Link](line)

• Opens two files at once using multiple context managers.

• Reads each line from the input file.

• The condition not [Link]('#') skips comment lines.

• Writes only valid lines to the output file.

Applications

• Removing comments or blank lines.

• Extracting specific text patterns.

• Reformatting files for reports or analysis.

• You can add more filters, e.g., skipping empty lines:

20
PYTHON PROGRAMMING-1BPLC105B MODULE-3
• if [Link]() and not [Link]('#'):

• [Link](line)

• This method is memory-efficient since it reads one line at a time.

• Ideal for log files, data cleaning, and preprocessing tasks.

2.7 Directories

A directory (or folder) is a container for files and other directories.


A file system is the structure used by an operating system to organize and store data on a disk.

Example (Unix-based)

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

wordlist = [Link]()

print(wordlist[:6])

• The file is located using its path (/usr/share/dict/words).

• readlines() reads all lines into a list.

• Prints the first few lines.

Windows Example

open("C:\\temp\\[Link]", "r")

or

open("c:/temp/[Link]", "r")

• / and \ cannot be used inside filenames — they separate folders.

• Use [Link] module for safer file handling across systems.

Example

import os

path = [Link]("data", "[Link]")

print(path)

On Linux → data/[Link]
On Windows → data\\[Link]

The current directory is where the Python program is running.

• Use [Link]() to get the current working directory.

• You can use:

o [Link]() → to list files in a directory.


21
PYTHON PROGRAMMING-1BPLC105B MODULE-3
o [Link]() / [Link]() → to create new folders.

2.8 Fetching Something from the Web

Concept

Python can fetch data directly from the internet (web URLs) and process or save it to local files.

Example using urllib:

import [Link]

url = "[Link]

destination_filename = "[Link]"

[Link](url, destination_filename)

• Downloads the content of the URL.

• Saves it to [Link] in the current directory.

• The urlretrieve() function handles both downloading and saving.

Requirements

• The URL must be valid and accessible.

• The user must have permission to write to the destination file.

• If using a proxy or restricted network, configuration may be needed.

Security Tip

Always verify the source of data — websites can change or become unsafe.

Alternative Method: Using requests Module

import requests

url = "[Link]

response = [Link](url)

print([Link])

• [Link]() fetches the web content.

• [Link] returns the text content of the page.

Reading Line by Line

22
PYTHON PROGRAMMING-1BPLC105B MODULE-3
for line in response:

print(line)

Advantages of requests

• Simpler syntax.

• Easier to handle headers, cookies, and status codes.

• Not part of Python’s standard library (install using pip install requests).

Common Use Cases

• Downloading data for analysis.

• Reading live weather data or stock prices.

• Building web crawlers or APIs.

23

You might also like