0% found this document useful (0 votes)
9 views29 pages

Module 3

The document provides an overview of Python dictionaries, including their structure, operations, and methods for accessing and modifying data. It also covers concepts of aliasing and copying in Python, as well as an introduction to NumPy, a library for numerical computations with arrays and matrices. Key features of NumPy, such as array creation, dimensions, and indexing, are discussed with examples.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views29 pages

Module 3

The document provides an overview of Python dictionaries, including their structure, operations, and methods for accessing and modifying data. It also covers concepts of aliasing and copying in Python, as well as an introduction to NumPy, a library for numerical computations with arrays and matrices. Key features of NumPy, such as array creation, dimensions, and indexing, are discussed with examples.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Module 3

1. Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
 Key-value pairs
 Unordered
We can construct or create dictionary
like:

 X={1:’A’,2:’B’,3:’c’}
 X=dict([(‘a’,3) (‘b’,4)]
 X=dict(‘A’=1,’B’ =2)
Example:
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}

>>> dict1 {'brand': 'mrcet', 'model': 'college', 'year': 2004}

1.1 Operations and methods


Methods that are available with dictionary are tabulated below. Some of them have already been
used in the above examples.

Method Description

clear() Remove all items form the dictionary

Copy() Return a shallow copy of the dictionary.

fromkeys(seq[, v]) Return the value of key. If key doesnot exit, return d
(defaults to None).

get(key[,d]) Return the value of key. If key doesnot exit, return d


(defaults to None).

items() Return a new view of the dictionary's items (key, value).

keys() Return a new view of the dictionary's keys.

Remove the item with key and return its value or d if key is not
pop(key[,d]) found. If d is not provided and key is not found, raises
KeyError.

42
popitem() Remove and return an arbitary item (key, value). Raises
KeyError if the dictionary is empty.

If key is in the dictionary, return its value. If not, insert key


setdefault(key[,d]) with a value of d and
return d (defaults to None).

Update the dictionary with the key/value pairs from other,


update() overwriting existing keys

values() Return a new view of the dictionary's values

To access specific value of a dictionary, we must pass its key,


>>> dict1 = {"brand":"Toyota","model":"car","year":2004}
>>> x=dict1["brand"] >>> x
'Toyota'
---------------------
To access keys and values and items of dictionary:
>>> dict1 = {"brand":" Toyota ","model":"car","year":2004}
>>> [Link]()
dict_keys(['brand', 'model', 'year'])
>>> [Link]()
dict_values([' Toyota ', 'car', 2004])
>>> [Link]()
dict_items([('brand', ' Toyota '), ('model', 'car'), ('year', 2004)]) -----------------------------------------
>>> for items in [Link]():
print(items)
Toyota
car
2004
>>> for items in [Link]():
print(items)
brand
model
year

>>> for i in [Link]():


print(i)
('brand', 'Toyota')
('model', 'car')
('year', 2004)

43
Operation of Dictionaries:
 Add/change
 Remove
 Length
 Delete
Add/change values: You can change the value of a specific item by referring to its key name
>>> dict1 = {brand":"Toyota","model":"car","year":2004}
>>> dict1["year"]=2005
>>> dict1 = {'brand': 'Toyota', 'model': 'car', 'year': 2005}
Remove(): It removes or pop the specific item of dictionary.

>>> dict1 = {"brand":"Toyota","model":"car","year":2004}


>>> print([Link]("model"))
car
>>> dict1 {'brand': 'Toyota', 'year': 2005}
Delete: Deletes a particular item.

>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}


>>> del x[5]
>>> x
Length: we use len() method to get the length of dictionary.
>>>{1: 1, 2: 4, 3: 9, 4: 16} {1: 1, 2: 4, 3: 9, 4: 16}
>>> y=len(x)
>>> y
4
Iterating over (key, value) pairs:
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> for key in x: print(key, x[key])
11
24
39
4 16
5 25
>>> for k,v in [Link]():
print(k,v)
11
24
39
4 16
5 25

44
>>> customers = [{"uid":1,"name":"John"}, {"uid":2,"name":"Smith"},
{"uid":3,"name":"Andersson"}, ]
>>> >>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name': 'Andersson'}]

## Print the uid and name of each customer


>>> for x in customers:
print(x["uid"], x["name"])

1 John
2 Smith
3 Andersson

## Modify an entry, This will change the name of customer 2 from Smith to Charlie
>>> customers[2]["name"]="charlie"
>>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name': 'charlie'}]

## Add a new field to each entry


>>> for x in customers:
x["password"]="123456" # any initial value
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 2, 'name': 'Smith', 'password':'123456'},
{'uid': 3, 'name': 'charlie', 'password': '123456'}]

## Delete a field
>>> del customers[1]
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 3, 'name': 'charlie', 'password': '123456'}]
>>> del customers[1]
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}]

## Delete all fields


>>> for x in customers: del x["uid"]
>>> x
{'name': 'John', 'password': '123456'}

45
2. Aliasing and copying
 Definition: When two variables refer to the same object in memory.
 Effect: Changes made through one variable are reflected in the other.
a = [1, 2, 3]
b = a # aliasing
b[0] = 99
print(a) # [99, 2, 3] — a is also changed

 Why it happens: Assignment in Python does not create a copy; it just binds a new name to
the same object.
Copying:

Copying creates a new object with the same content.

Shallow Copy

 Creates a new object but does not recursively copy nested objects.
 Methods:

 [Link]() (for lists)


 copy. copy(obj) from the copy module
 Slicing: new_list = old_list[:]
Example:

import copy
a = [[1, 2], [3, 4]]
b = copy. copy(a) # shallow copy
b[0][0] = 99
print(a) #[[99, 2],[3, 4]] —inner list is still shared.

3. NumPy

NumPy stands for ‘Numerical Python’ or ‘Numeric Python’.

It is an open source module of Python which provides fast mathematical computation on


arrays and matrices. Since, arrays and matrices are an essential part of the Machine Learning
ecosystem, NumPy along with Machine Learning modules like Scikit-learn, Pandas, Matplotlib,
TensorFlow, etc. completes the Python Machine Learning Ecosystem.

NumPy is a Python library used for working with arrays.

46
It also has functions for working in domain of linear algebra, Fourier transform, and
matrices. NumPy was created in 2005 by Travis Oliphant.

It is an open source project and you can use it freely.

NumPy stands for Numerical Python.

Uses:

In Python we have lists that serve the purpose of arrays, but they are slow to process.
NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting functions that
make working with ndarray very easy.
Arrays are very frequently used in data science, where speed and resources are very
important. Data Science: is a branch of computer science where we study how to store, use and
analyze data for deriving information from it.

Numpy Faster than Lists:


NumPy arrays are stored at one continuous place in memory unlike lists, so processes
can access and manipulate them very efficiently.
This behavior is called locality of reference in computer science.
This is the main reason why NumPy is faster than lists. Also it is optimized to work with
latest CPU architectures.
Numpy Written Lanuguage:
NumPy is a Python library and is written partially in Python, but most of the parts that
require fast computation are written in C or C++.

import NumPy
Once NumPy is installed, import it in your applications by adding the import keyword:
import numpy

Example:
import numpy

arr=[Link]([1, 2, 3, 4, 5])
print(arr)

file name : simple_numpy.py

NumPy as np

NumPy is usually imported under the np alias.

47
alias: In Python alias are an alternate name for referring to the same thing.

Create an alias with the as keyword while importing:

import numpy as np

Now the NumPy package can be referred to as np instead of numpy.

Example

import numpy as np
arr=[Link]([1, 2, 3, 4, 5])
print(arr)
file name : simple_numpy.py
Checking NumPy Version
The version string is stored under __version__ attribute.
Example
type(): This built-in Python function tells us the type of the object passed to it. Like in above
code it shows that arr is [Link]

import numpy as np
print(np.__version__)

file name : simple_numpy.py

NumPy Creating Arrays


Create a NumPy ndarray Object
NumPy is used to work with arrays.
The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
Example:
import numpy as np

arr = [Link]([1, 2, 3, 4, 5])


print(arr)

print(type(arr))

file name : simple_numpy.py

To create an ndarray, we can pass a list, tuple or any array-like object into the array()
method, and it will be converted into an ndarray:

48
Example:Use a tuple to create a NumPy array:

import numpy as np

arr=[Link]((1, 2, 3, 4, 5))
print(arr)

Dimensions in Arrays

A dimension in arrays is one level of array depth (nested arrays).


nested array: are arrays that have arrays as their elements.

0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
Example: Create a 0-D array with value 42

import numpy as np
arr=[Link](42)
print(arr)
file name : array_type.py

1-D Array

An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
These are the most common and basic arrays.
Example: Create a 1-D array containing the values 1,2,3,4,5:

import numpy as np

arr=[Link]([1, 2, 3, 4, 5])
print(arr)

File name: array_type.py

2-D Arrays

An array that has 1-D arrays as its elements is called a 2-D array.
These are often used to represent matrix or 2nd order tensors.
NumPy has a whole sub module dedicated towards matrix operations called [Link]

49
Example: Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:

import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
print(arr)
Or
arr = [Link]([[1, 2, 3], ['a', 'b', 'c']])
print(arr)

output :

[['1''2''3']
['a' 'b' 'c']

file name : array_type.py

3-D arrays

An array that has 2-D arrays (matrices) as its elements is called 3-D array.
These are often used to represent a 3rd order tensor.
Example: Create a 3-D array with two 2-D arrays, both containing two arrays with the
values 1,2,3 and 4,5,6:

import numpy as np

arr=[Link]([[[1, 2, 3],[4, 5, 6]],[[1, 2, 3],[4, 5, 6]]])


print(arr)

Check Number of Dimensions?

NumPy Arrays provides the ndim attribute that returns an integer that tells us how many
dimensions the array have.

Example: Check how many dimensions the arrays have:

import numpy as np
a = [Link](42)
b = [Link]([1, 2, 3, 4, 5])
c = [Link]([[1, 2, 3], [4, 5, 6]])
d = [Link]([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print([Link])
print([Link])
print([Link])
print([Link])
50
file name : check_dimension.py

NumPy Array Indexing Access Array Elements Array indexing is the same as accessing an array
element.

You can access an array element by referring to its index number.

The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the
second has index 1 etc.

Example: Get the first element from the following array:

import numpy as np

arr = [Link]([1, 2, 3, 4])


print(arr[0])

Example: Get the second element from the following array.

import numpy as np

arr = [Link]([1, 2, 3, 4]) print(arr[1])

Example: Get third and fourth elements from the following array and add them.

import numpy as np

arr = [Link]([1, 2, 3, 4])

print(arr[2] + arr[3])

Access 2-D Arrays

To access elements from 2-D arrays we can use comma separated integers representing the
dimension and the index of the element.

Example: Access the 2nd element on 1st dim:

import numpy as np

arr = [Link]([[1,2,3,4,5], [6,7,8,9,10]])

print('2nd element on 1st dim: ', arr[0, 1])

51
Example: Access the 5th element on 2nd dim:

import numpy as np

arr = [Link]([[1,2,3,4,5], [6,7,8,9,10]])

print('5th element on 2nd dim: ', arr[1, 4])

Access 3-D Arrays

To access elements from 3-D arrays we can use comma separated integers representing the
dimensions and the index of the element.
Example: Access the third element of the second array of the first array:

import numpy as np

arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])

Negative Indexing

Use negative indexing to access an array from the end.


Example: Print the last element from the 2nd dim:

import numpy as np

arr=[Link]([[1,2,3,4,5],[6,7,8,9,10]])

print('Last element from 2nd dim: ', arr[1, -1])

3.1 Array Indexing, Slicing, and Broadcasting


Most of this lecture will be a review of basic indexing and slicing operations, albeit within the
context of NumPy arrays. Therefore, there will be some additional functionality that is critical to
understand. By the end of this lecture, you should be able to:

 Use "fancy indexing" in NumPy arrays


 Create boolean masks to pull out subsets of a NumPy array
 Understand array broadcasting for performing operations on subsets of NumPy arrays
Hopefully, you recall basic indexing and slicing from Lecture 4. If not, please go back and
refresh your understanding of the concept.

52
In [1]: li = ["this", "is", "a", "list"]

print(li)
print(li[1:3]) # Print element 1 (inclusive) to 3 (exclusive) print(li[2:]) #
Print element 2 and everything after that
print(li[:-1]) # Print everything BEFORE element -1 (the last one)

['this', 'is', 'a', 'list'] ['is', 'a']


['a', 'list']
['this', 'is', 'a']

With NumPy arrays, all the same functionality you know and love from lists is still there.
In [2]: import numpy as np
x = [Link]([1, 2, 3, 4, 5])
print(x)
print(x[1:3])
print(x[2:])
print(x[:-1])

output:
[1,2,3,4,5]
[2,3]
[2]
These operations all work whether you’re using Python lists or NumPy arrays.
The first place in which Python lists and NumPy arrays differ is when we get to
multidimen- sional arrays. We’ll start with matrices.
To build matrices using Python lists, you basically needed "nested" lists, or a list
containing lists:
In [3]: python_matrix = [[1, 2, 3], [4, 5, 6], [7,8,9]]
Print (python_matrix)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
To build the NumPy equivalent, you can basically just feed the Python list-matrix
into the NumPy array method:
In [4]: numpy_matrix = [Link](python_matrix)
print(numpy_matrix)
[[1 2 3]
[4 5 6]

[7 8 9]]

53
The real difference, though, comes with actually indexing these elements. With Python
lists, you can index individual elements only in this way:

In [5]: print(python_matrix) # The full list-of-lists

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In [6]: print(python_matrix[0]) # The inner-list at the 0th position of

t h e o u t e r - l i s t [1, 2, 3]

In [7]: print(python_matrix[0][0]) # The 0th element of the 0th inner-list


With NumPy arrays, you can use that same notation...or you can use comma-separated

indices

In [8]: print(numpy_matrix)

numpy matrix

[[1 2 3] [4 5 6] [7 8 9]]

In [9]: print(numpy_matrix[0])

[1 2 3]

In [10]: print(numpy_matrix[0, 0]) # Note the comma-separated format!

When you index NumPy arrays, the nomenclature used is that of an axis: you are indexing
specific axes of a NumPy array object. In particular, when access the .shape attribute on a NumPy
array, that tells you two things:

1:How many axes there are. This number is len([Link]), or the number of elements
in the tuple returned by .shape. In our above example, numpy_matrix.shape would return (3,
3), so it would have 2 axes (since there are two numbers--both 3s).

54
2:How many elements are in each axis. In our above example, where numpy_matrix.shape
returns (3, 3), there are 2 axes (since the length of that tuple is 2), and both axes have 3 elements
(hence the numbers--3 elements in the first axis, 3 in the second).
Here’s the breakdown of axis notation and indices used in a 2D NumPy array:
As with lists, if you want an entire axis, just use the colon operator all by itself:
In [11]: x = [Link]([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ])
print(x)
[[1 2 3] [4 5 6] [7 8 9 ]]
In [12]: print(x[:, 1]) # Take ALL of axis 0, and one index of axis 1.
[2 5 8]

55
Example
import numpy as np

# 1. Creating arrays
arr1 = [Link]([1, 2, 3, 4]) # 1D array
arr2 = [Link]([[1, 2], [3, 4]]) # 2D array

# 2. Array properties
print("arr1:", arr1)
print("Shape:", [Link])
print("Data type:", [Link])

# 3. Creating special arrays


zeros = [Link]((2, 3)) # 2x3 array of zeros
ones = [Link]((3, 2)) # 3x2 array of ones
range_arr = [Link](0, 10, 2) # Even numbers from 0 to 8
linspace_arr = [Link](0, 1, 5) # 5 evenly spaced numbers between 0 and 1

# 4. Element-wise operations
sum_arr = arr1 + 10
mul_arr = arr1 * 2

# 5. Mathematical functions
sqrt_arr = [Link](arr1)
mean_val = [Link](arr1)

# 6. Matrix operations
mat1 = [Link]([[1, 2], [3, 4]])
mat2 = [Link]([[5, 6], [7, 8]])
dot_product = [Link](mat1, mat2) # Matrix multiplication

# Output results
print("\nZeros:\n", zeros)
print("Ones:\n", ones)
print("Range array:", range_arr)
print("Linspace array:", linspace_arr)
print("Sum array:", sum_arr)
print("Multiply array:", mul_arr)
print("Square roots:", sqrt_arr)
print("Mean value:", mean_val)
print("Dot product:\n", dot_product)

56
Creating a Matrix

To create a matrix in NumPy, you can use the [Link]() function, which converts a list of lists
into a NumPy array. For example:

import numpy as np
# Creating a 2x2 matrix
matrix1 = [Link]([[1, 3], [5, 7]])
print("2x2 Matrix:\n", matrix1)
# Creating a 3x3 matrix
matrix2 = [Link]([[2, 3, 5], [7, 14, 21], [1, 3, 5]])
print("\n3x3 Matrix:\n", matrix2)

Matrix Operations
NumPy provides several functions to perform common matrix operations:
Matrix Addition
To add two matrices element-wise, you can use the + operator:
A = [Link]([[2, 4], [5, -6]])
B = [Link]([[9, -3], [3, 6]])
C=A+B
print(C)
Matrix Multiplication
For matrix multiplication, use the [Link]() function:
A = [Link]([[3, 6, 7], [5, -3, 0]])
B = [Link]([[1, 1], [2, 1], [3, -3]])
C = [Link](A, B)
print(C)
Transpose of a Matrix
To transpose a matrix, use the [Link]() function or the .T attribute:
A = [Link]([[1, 1], [2, 1], [3, -3]])
print([Link]())
Inverse of a Matrix

To calculate the inverse of a matrix, use the [Link]() function. Note that only square
matrices with a non-zero determinant have an inverse:

A = [Link]([[1, 3, 5], [7, 9, 2], [4, 6, 8]])


inverse_A = [Link](A)
print(inverse_A)

57
Determinant of a Matrix
To find the determinant of a matrix, use the [Link]() function:
A = [Link]([[1, 2, 3], [4, 5, 1], [2, 3, 4]])
det_A = [Link](A)
print(det_A)
Flattening a Matrix
To convert a matrix into a 1D array, use the flatten() method:
A = [Link]([[1, 2, 3], [4, 5, 7]])
flattened_A = [Link]()
print(flattened_A)
Accessing Elements, Rows, and Columns
You can access elements, rows, and columns of a matrix using indexing and slicing:
A = [Link]([[1, 4, 5, 12], [-5, 8, 9, 0], [-6, 7, 11, 19]])
# Accessing elements
print("A[0][0] =", A[0][0]) # First element of first row
print("A[1][2] =", A[1][2]) # Third element of second row
print("A[-1][-1] =", A[-1][-1]) # Last element of last row
# Accessing rows
print("A[0] =", A[0]) # First row
print("A[2] =", A[2]) # Third row
# Accessing columns
print("A[:,0] =", A[:,0]) # First column
print("A[:,3] =", A[:,3]) # Fourth column

3.2 Masking in Numpy:


import numpy as np
arr = [Link]([1, 5, 8, 2, 9, 4])
mask = arr > 4 # Create a boolean mask where elements are greater than 4
print(mask)
# Output: [False True True False True False]
selected_elements = arr[mask] # Select elements where the mask is True
print(selected_elements)
# Output: [5 8 9]

3.3 NumPy Data Types


Data Types in Python

By default Python have these data types:

 strings - used to represent text data, the text is given under quote marks. e.g. "ABCD"

58
 integer - used to represent integer numbers. e.g. -1, -2, -3
 float - used to represent real numbers. e.g. 1.2, 42.42
 boolean - used to represent True or False.
 complex - used to represent complex numbers. e.g. 1.0 + 2.0j, 1.5 + 2.5j
Data Types in NumPy

NumPy has some extra data types, and refer to data types with one character, like i for
integers, u for unsigned integers etc.

Below is a list of all data types in NumPy and the characters used to represent them.

 i - integer
 b - boolean • O - object
 u - unsigned integer • S - string
 f – float • U - unicode string
 c - complex float • V - fixed chunk of memory for other
 m - timedelta type ( void )
 M - datetime

Checking the Data Type of an Array

The NumPy array object has a property called dtype that returns the data type of the array:
Example: Get the data type of an array object:

import numpy as np

arr = [Link]([1, 2, 3, 4])


print([Link])

Example: Get the data type of an array containing strings:

import numpy as np

arr=[Link](['apple', 'banana', 'cherry'])


print([Link])

Creating Arrays with a Defined Data Type


We use the array () function to create arrays, this function can take an optional
argument: dtype that allows us to define the expected data type of the array elements:
Example: Create an array with data type string:
import numpy as np
arr = [Link]([1, 2, 3, 4], dtype='S')
print(arr)
print ([Link])

For i, u, f, S and U we can define size as well.

59
Example: Create an array with data type 4 bytes integer:
import numpy as np
arr = [Link]([1, 2, 3, 4], dtype='i4')
print(arr)
print([Link])
Note:
[What if a Value Can Not Be Converted?
If a type is given in which elements can't be casted then NumPy will raise a
ValueError: In Python ValueError is raised when the type of passed argument to a
function is unexpected/incorrect.
Example:A non integer string like 'a' cannot be converted to integer
(will raise an error):
import numpy as np
arr = [Link](['a', '2', '3'],
dtype= Converting Data Type on Existing Arrays
The best way to change the data type of an existing array, is to make a copy of the
array with
the astype() method.
The astype() function creates a copy of the array, and allows you
Parameter.
The data type can be specified using a string, like
the data type directly like float for float and
Example: Change data type from float to integer by using ‘i’ as parameter
value
import numpy as
arr = [Link]([1.1,2.1,3.1])
newarr = [Link](‘i’)
print(newarr)
print([Link])
4. Files
In Python, a file represents a named location on a storage device (like a hard drive) used
to store data permanently. Unlike data stored in memory (RAM), which is lost when a program
ends or the computer shuts down, data in files persists.
Python provides built-in functions and modules for interacting with files, a process
commonly referred to as File Handling. This allows programs to:
 Create: new files.
 Open: existing files for various operations.
 Read: data from files.
 Write: data to files.
 Close: files to release system resources.

60
4.1 Types of Files in Python:
Text Files:
These files contain human-readable characters, with each line typically terminated by a newline
character (\n). Examples include .txt, .py, .csv, and .json files.
Binary Files:
These files store data in a non-human-readable, binary format (sequences of 0s and 1s). They
require specific programs or libraries to interpret their contents. Examples include images, audio
files, and compiled executables.
Basic File Operations in Python:

Opening the file: Using the open() function, specifying the file path and the desired mode
(e.g., 'r' for read, 'w' for write, 'a' for append). This returns a file object.

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


Performing operations: Using methods associated with the file object, such
as read(), write(), readline(), or readlines().
content = file_object.read()

Closing the file: Using the close() method to release resources. It's crucial to close files after
use.
file_object.close()

Context Managers for File Handling:


The with open(...) as ...: statement is the recommended way to handle files, as it automatically
ensures files are closed even if errors occur.
with open("[Link]", "w") as file_object:
file_object.write("Hello, world!")

4.2 writing our First file in python


 Open a text editor: Use any text editor (like Notepad on Windows, TextEdit on macOS, or a
code editor like VS Code, Sublime Text, or PyCharm).
 Create a new file: In your text editor, create a new file and save it with a .py extension. For
example, save it as my_first_file.py.
Example:
# Open the file in write mode ('w')
# If the file doesn't exist, it will be created.
# If the file exists, its content will be overwritten.
with open("my_output.txt", "w") as file:

61
[Link]("Hello from Python!\n")
[Link]("This is my first time writing to a file.\n")
[Link]("I'm learning Python file handling.")
print("Content successfully written to my_output.txt")
Save the file: Save the changes to my_first_file.py.
Run the Python script:
 Open a terminal or command prompt.
 Navigate to the directory where you saved my_first_file.py.
 Run the script using the Python interpreter:

python my_first_file.py
output:

Hello from Python!


This is my first time writing to a file.
I'm learning Python file handling.

4.3 Reading a file line-by-line

To read a file line by line in Python, the most common and efficient method involves
iterating directly over the file object. This approach handles opening and closing the file
automatically and is memory-efficient, especially for large files, as it reads one line at a time
without loading the entire file into memory.

# Create a sample file for demonstration


with open("[Link]", "w") as f:
[Link]("This is the first line.\n")
[Link]("This is the second line.\n")
[Link]("And the third line.\n")
# Read the file line by line
try:
with open("[Link]", "r") as file:
for line in file:
# Each 'line' variable will contain a line from the file,
# including the newline character at the end (e.g., '\n').
# To remove the newline character, use .strip()
print([Link]())
except FileNotFoundError:
print("Error: The file '[Link]' was not found.")
except Exception as e:

62
print(f"An error occurred: {e}")

4.4 Turning a file into a list of lines

To convert a file into a list of lines in Python, the readlines() method or list
comprehension with strip() are common approaches.

file_path = "my_file.txt"
# Create a sample file for demonstration
with open(file_path, "w") as f:
[Link]("First line\n")
[Link]("Second line\n")
[Link]("Third line")
with open(file_path, "r") as file:
lines = [Link]()
print(lines)

output:
['First line\n', 'Second line\n', 'Third line']

Python File Modes


Mode Description
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it
exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it. Creates a new file if it
does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and w

63
Example
f = open("[Link]", "r")
print([Link]())

Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how many
characters you want to return:

Example

Return the 5 first characters of the file:

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

Read Lines

You can return one line by using the readline() method:

Example

Read one line of the file:

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

By calling readline() two times, you can read the two first lines:

Example

Read two lines of the file:

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

print([Link]())
print([Link]())
Run example »

By looping through the lines of the file, you can read the whole file, line by line:

64
Example

Loop through the file line by line:

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

for x in f:

print(x)

Close Files

It is a good practice to always close the file when you are done with it.

Example

Close the file when you are finish with it:

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

[Link]()un example »

Note: You should always close your files, in some cases, due to buffering, changes made to a
file may not show until you close the file.

Write to an Existing File

To write to an existing file, you must add a parameter to the open()


function:

"a" - Append - will append to the end of the file "w" - Write -

will overwrite any existing content

Example

Open the file "[Link]" and append content to the file:

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

[Link]("Now the file has more content!") [Link]()

#open and read the file after the appending: f =


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

65
print([Link]())

Open the file "[Link]" and overwrite the content:

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

[Link]("Woops! I have deleted the content!") [Link]()

#open and read the file after the appending: f =


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

print([Link]())
Note: the "w" method will overwrite the entire file.

Create a New File

To create a new file in Python, use the open() method, with one of the following parameters:

"x" - Create - will create a file, returns an error if the file exist "a" - Append -

will create a file if the specified file does not exist "w" - Write - will create a file if

the specified file does not exist

Example

Create a file called "[Link]":

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

Result: a new empty file is created!

Example

Create a new file if it does not exist: f =

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

Delete a File

To delete a file, you must import the OS module, and run its [Link]()
function:
Example

Remove the file "[Link]"


66
4.5 Binary Files
Binary files in Python are used to store non-textual data in its raw, byte-level format. Unlike text
files, which store human-readable characters, binary files contain sequences of bytes representing various
data types like images, audio, video, or serialized Python objects.

 on-human readable:
The content is not directly decipherable by humans without specific tools or programs.
 Efficient for computers:
Storing data in its raw binary form is highly efficient for computer processing.
 No line delimiters:
Unlike text files, binary files do not typically use special characters like newline
characters to mark the end of a line.
Working with binary files in Python:
Opening the file: Use the built-in open() function with the appropriate binary mode:
 'rb' for reading binary data.
 'wb' for writing binary data.
 'ab' for appending binary data.

Example: with open('[Link]', 'wb') as file:


# Write binary data here

Reading and writing data:


 When writing, ensure the data is in bytes format (e.g., using b'string' for byte
strings or bytearray() for byte arrays).
 When reading, the read() method will return bytes.

Eample:
# Writing binary data
data_to_write = b'Hello, Binary World!'
with open('[Link]', 'wb') as f:
[Link](data_to_write)

# Reading binary data


with open('[Link]', 'rb') as f:
read_data = [Link]()
print(read_data)

67
Examples:
# Creating a bytes object from a string literal
b_literal = b"hello"
print(f"b_literal: {b_literal}")
print(f"Type of b_literal: {type(b_literal)}")

# Creating a bytes object from a list of integers


b_list = bytes([72, 101, 108, 108, 111]) # ASCII values for "Hello"
print(f"b_list: {b_list}")

# Accessing individual bytes


print(f"First byte of b_literal: {b_literal[0]}") # Output: 104 (ASCII value of
'h')

# Slicing a bytes object


print(f"Slice of b_literal: {b_literal[1:3]}") # Output: b'el'

Output:
b_literal: b'hello'
Type of b_literal: <class 'bytes'>
b_list: b'Hello'
First byte of b_literal: 104
Slice of b_literal: b'el'

4.6 Directories:

Getting the Current Working Directory:


import os
current_directory = [Link]()
print(f"Current working directory: {current_directory}")

Creating a Directory:
import os
new_dir_name = "my_new_directory"
try:
[Link](new_dir_name)
print(f"Directory '{new_dir_name}' created successfully.")
except FileExistsError:
print(f"Directory '{new_dir_name}' already exists.")

68
Listing Directory Contents:
import os
# List contents of the current directory
contents = [Link](".")
print(f"Contents of current directory: {contents}")
# List contents of a specific directory (if it exists)
if [Link]("my_new_directory"):
dir_contents = [Link]("my_new_directory")
print(f"Contents of 'my_new_directory': {dir_contents}")

Changing the Current Working Directory:


import os
original_cwd = [Link]()
print(f"Original CWD: {original_cwd}")
# Change to a different directory (assuming it exists)
if [Link]("my_new_directory"):
[Link]("my_new_directory")
print(f"New CWD: {[Link]()}")
# Change back to the original directory
[Link](original_cwd)
print(f"CWD after changing back: {[Link]()}")

with statement in file handling:


The with statement in Python is a crucial construct for safe and efficient file handling,
primarily because it ensures that resources, such as open files, are properly managed and closed
automatically, even if errors occur.
Reading file
with open("my_file.txt", "r") as file:
content = [Link]()
print(content)
# The file 'my_file.txt' is automatically closed here
Writing file
with open("new_file.txt", "w") as file:
[Link]("This is a new line of text.")
[Link]("\nAnother line.")
# The file 'new_file.txt' is automatically closed here

69
4.7 Fetching something from the Web
To fetch files from the web using Python, you can use the requests library, which allows you to
make HTTP requests to retrieve data from web pages. Here's a simple example to download a file
from a web URL:
import requests
url = '[Link]
response = [Link](url)
content = [Link]
print(content)
This code fetches the content of the specified URL and prints it to the console. If the URL points
to a file, you can save it to your local machine using the with open() statement:
import requests
import os
url = '[Link]
response = [Link](url)
content = [Link]
with open('[Link]', 'wb') as f:
[Link](content)
print('File downloaded successfully')

70

You might also like