Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

Python Programming

(CSE3011, LP, 03)

Dr. JITENDRA P S MATHUR (100526)


Assistant Professor Grade-I,
School of Computing Science and Engineering,
VIT Bhopal University, Bhopal
Course Objectives
This course will introduce the Python Programming
language, its functionality, code constructs, and its
applications. This course is devised for following
objectives.

1. To study object oriented paradigm in Python.


2. To develop their skill set using Python.
3. To familiarize with the functionalities and applications
of Python
Course Outcomes

• Understand and use the Object Oriented paradigm in


Python.

• Use the IO model in Python to read and write disk files.

• Write Python programs using collections, regular


expression, classifying and categorizing text.
Student Outcomes (SO)
1. An ability to analyze a problem, identify and define the
computing requirements appropriate to its solution.
2. An ability to design, implement and evaluate a system
/computer‐based system, process, component or program
to meet desired needs
3. Design and conduct experiment as well as analyze and
interpret data.
4. An ability to use current techniques, skills and tools
necessary for computing engineering practice.
5. An ability to apply mathematical foundations, algorithmic
principles and computer science theory in the modeling
and design of computer-based systems (CS)
Syllabus
Continue…
List of Experiments
Unit-IV
• File Handling, Writing Data to a File, Reading
Data From a File - Additional File Methods:
Using Pipes as Data Streams, Handling IO
Exceptions, Working with Directories, Metadata,
File Organization, Database Programming -
Generic Database Connectivity using ODBC,
Postgres connection in Python, MySQL
connection in Python.
What is a file?
• File is a named location on disk to store related
information. It is used to permanently store data in a
non-volatile memory (e.g. hard disk).
• Since, random access memory (RAM) is volatile which
loses its data when computer is turned off, we use files
for future use of the data.
• Hence, in Python, a file operation takes place in the
following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
File Handling
• File handling in Python is a powerful and versatile tool
that can be used to perform a wide range of operations.
• Python too supports file handling and allows users to
handle files i.e., to read and write files, along with many
other file handling options, to operate on files.
• The key function for working with files in Python is the
open() function.
TYPES OF FILES
1. Text file
• A text file can be understood as a sequence of characters
consisting of alphabets, numbers and other special
symbols.
• Files with extensions like .txt, .py, .csv, etc. are some
examples of text files.
• In ASCII, UNICODE or any other encoding scheme, the
value of each character of the text file is stored as bytes.

2. Binary Files
• Binary files are also stored in terms of bytes (0s and 1s),
but unlike text files, these bytes do not represent the ASCII
values of characters.
Continue..
• They represent the actual content such as image, audio,
video, compressed versions of other files, executable
files, etc.
• We need specific software to read or write the contents
of a binary file.
• These files are not human readable. Thus, trying to open
a binary file using a text editor will show some garbage
values.
• We can read and write both text and binary files through
Python programs.
OPENING AND CLOSING A TEXT FILE

• In real world applications, computer programs deal with


data coming from different sources like databases, CSV
files, HTML, XML, JSON, etc.
• We broadly access files either to write or read data from
it.
• Python has the IO module that contains different
functions for handling files.
Continue..
• To open a file in Python, we use the open() function. The syntax of
open() is as follows: file_object= open(file_name, access_mode)
• This function returns a file object called file handle which is stored
in the variable file_object.
• We can use this variable to transfer data to and from the file (read
and write) by calling the functions defined in the Python’s io
module.
• The file_object has certain attributes that tells us basic information
about the file,
• such as:
• <file.closed> returns true if the file is closed and false otherwise.
• <file.mode> returns the access mode in which the file was opened.
• <file.name> returns the name of the file.
File Open Modes in python
Modes Description

r Opens a file for reading only.


rb Opens a file for reading only in binary format.
r+ Opens a file for both reading and writing.

rb+ Opens a file for both reading and writing in binary format.

w Opens a file for writing only.


wb Opens a file for writing only in binary format.
w+ Opens a file for both writing and reading.

wb+ Opens a file for both writing and reading in binary format.

a Opens a file for appending.


ab Opens a file for appending in binary format.
a+ Opens a file for both appending and reading.

ab+ Opens a file for both appending and reading in binary format.
Example
The open command opens the file in reading mode and prints each line of
the file with for loop.

# a file named "file", will be opened with the reading mode.


file = open('file.txt', 'r')
# Each line will be printed one by one in the file
for each in file:
print (each)
Perform Write operation

• First of all, open it with a mode (read/write/append)


while you are ready to enter data to a file.

• Python provides a write() method to write a string or


bytes sequence to a file. This function returns a number
that is the size of data stored in a single Write call.
Continue…

• Read/Write to a File in Python


# Python code to create a file
file = open('file.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

In the above example, the statement f=open(“file.txt”, “w”) opens file.txt


in write mode, returns the file object and assigns it to the variable f in the
open method. “
Perform Read operation in python
• First of all, to read data from a file, you need to open it in
reading mode. You can then call any of the Python
methods for reading from a file.
• readline(): read characters from the current reading
position to the newline character.
• read(chars): reads the number of characters that are
specified starting from the current position.
• readlines(): reads all lines until file end and returns an
object list.
Example
Read from a File in Python

• with open('app.log', 'w', encoding = 'utf-8') as f:


• file.write('my first file\n') #first line
• file.write('This file\n') #second line
• file.write('contains three lines\n') #third line
• f = open('app.log', 'r', encoding = 'utf-8')
• print(file.read(10)) # read the first 10 data
• #'my first f'
• print(file.read(4)) # read the next 4 data
• #'file\n'
• print(file.read()) # read in the rest till end of file
• #'This file\ncontains three lines\n'
• print(file.read()) # further reading returns empty sting
• #''
Other methods

1. writelines() method
• The file object also has writelines() method to write
items in a list object to a file. The newline characters ("\
n) should be the part of the string.
Example
• f=open("python.txt","w")
• f.writelines(lines)
• f.close()

2. readline() method
• This method reads current line till it encounters newline
character.
Continue…
Example
• f=open('python.txt','r')
• f.readline()
• f=open("python.txt","r")
• while True:
• line=f.readline()
• if line=='':break
• print (line)
• f.close()

3. Exception in File Handling


File operation is subject to occurrence of exception. If file
could not be opened, OSError is raised and if it is not found,
FileNotFoundError is raised.
Continue…
4. Using Pipes as Data Streams os.pipe()

• OS module in Python provides functions for interacting


with the operating system.

• This module provides a portable way of using operating


system dependent functionality.

• It used to create a pipe. A pipe is a method to pass


information from one process to another process.

See code
Working with Directories
• Directories are a way of storing, organizing, and separating
the files on a computer.
• Python contains several modules that has a number of built-
in functions to manipulate and process data.
• Every process in the computer system will have a directory
associated with it, which is known as Current Working
Directory(CWD). os.chdir() method is used to change it.

• The modules that provide the functionalities are listed below:


1. os and os.path
2. filecmp
3. tempfile
4. shutil
1. os and os.path

• The os module is used to handle files and directories in


various ways. It provides provisions to
create/rename/delete directories.
• It allows one to copy files from one directory to another.
• os.mkdir(name) method to create a new directory.
• By default it creates the new directory in the current
working directory.
• Example
import os
# creates in current working directory
os.mkdir('new_dir')
# creates in D:\
os.mkdir('D:/new_dir')
2. filecmp
• This module provides various functions to perform comparison
between files and directories.
• To compare the directories, an object has to be created for the class
filecmp.dircmp that describes which files to ignore and which
files to hide from the functions of this class.

• Example

import filecmp as fc
import os
dir_1 = dir_2 = os.getcwd()
# creating object and invoking constructor
d = fc.dircmp(dir_1, dir_2, ignore=None, hide=None)
print("comparison 1 :")
d.report()
3. tempfile
• This module is used to create temporary files and
directories.
• This creates the temporary files and directories in the
temp directories created by the Operating systems. For
windows, the temp files can be found at the following path:
profile/AppData/Local/temp
• mkdtemp() :
• It is used to create a temporary directory by passing the
parameters suffix, prefix and dir.

• Example
import tempfile as tf
f = tf.mkdtemp(suffix='', prefix='tmp')
print(f)
4. shutil
• This module is concerned with number of high-level
operations on files and directories. It allows
copying/moving directories from a source to destination.

• Syntax 1 shutil.copytree(s, d, symlinks=False,


ignore=None, copy_function=copy2,
ignore_dangling_symlinks=False):

• Syntax 2 shutil.rmtree(path, ignore_errors=False,


onerror=None):

• Syntax 3 shutil.move(s,d):
Practice set
1. Write a Python program to list only directories,
files and all directories, files in a specified path.
2. Write a Python program to get the size,
permissions, owner, device, created, last
modified and last accessed date and time of a
specified path.
3. Write a Python program to find the parent's
process ID, real user ID of the current process
and change the real user ID.
4. Write a Python program to run an operating
system command using the OS module.
Database Programming
• A database is nothing but an organized collection of data.
Data is organized into rows, columns and tables and it is
indexed to make it easier to find relevant information.

• Form/any user interface designed in any programming


language is Front End where as data given by database
as response is known as Back-End database.

• SQL is just a query language, it is not a database. To


perform SQL queries, we need to install any

• Database for example Oracle, MySQL, MongoDB,


PostGres SQL, SQL Server, DB2 etc
Continue…
• The Python standard for database interfaces is the Python DB-API.
Python Database API supports a wide range of database servers,
like msql , mysql, postgressql, Informix, oracle, Sybase etc.
• Following are the reason to choose python for database
programming
1. Programming more efficient and faster compared to other
languages.
2. Portability of python programs.
3. Support platform independent program development.
4. Python supports SQL cursors.
5. Python itself take care of open and close of connections.
6. Python supports relational database systems.
7. Porting of data from one dbms to other is easily possible as it
support large range of APIs for various databases.
About MYSQL
Its open-source nature, stability, and rich feature set, paired with ongoing
development and support from Oracle, have meant that internet-critical
organizations such as Facebook, Flickr, Twitter, Wikipedia, and YouTube
all employ MySQL backends.
Current Developer Oracle Corporation
MySQL AB (Then, briefly, Sun
Original Developer
Microsystems)
Current Stable Release 8.0.16 (on April 25, 2019)
Original Release May 23, 1995
License GPLv2 (or proprietary)
Primary language C and C++
Website https://www.mysql.com/
Open-source repository https://github.com/mysql/mysql-server
Interface python with SQL Database
• SQL Connectors
• We must download a separate DB API module for
each database we need to access.
• The DB API provides a minimal standard for
working with databases using Python structures
and syntax wherever possible.
• Any one of mysql connector or MySQLdb can be
used for database programming.
• 1. mysql-connector MySQL-Connector enables
Python programs to access MySQL databases,
using an API that is compliant with the Python
Database API Specification v2.0 (PEP 249).
Continue…
Steps to use mysql-connector
1. Download Mysql API ,exe file and install it.
(https://dev.mysql.com/downloads/connector/py
thon/)
2. Install Mysql-Python Connector (Open
command prompt and execute command) >pip
install mysql-connector
3. Now connect Mysql server using python
4. Write python statement in python shell import
mysql.connector If no error message is shown
means mysql connector is properly installed.
Continue…
• 2. MySQLdb is an interface for connecting to a
MySQL database server from Python. It implements
the Python Database API v2.0 and is built on top of
the MySQL C API.
Steps to use mysqlclient
1. First Upgrade pip command through > python –m
pip install – upgrade pip
2. Install mysqlclient through pip install mysqlclient 3.
After successful installation check through import
mysqldb
4. If it is installed no error will be displayed otherwise
error message will be displayed
Continue…
• Establish connection
• In following way we can establish a connection with
mysql database through mysql.connector. import
mysql.connector
mydb=mysql.connector.connect(host="localhost",user="
root",passwd="root“,database =“college”) print(mydb)

• Cursor object : The MySQLCursor class instantiates


objects that can execute operations such as SQL
statements.
Continue…
• How to create cursor object and use it import
mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root
",passwd="root") mycursor=mydb.cursor()
mycursor.execute("create database if not exists school")
mycursor.execute("show databases") for x in mycursor:
print(x)
How to create table at run time
• Here we are opening database school(through
connect() method) before student table creation.

import mysql.connector
mydb=mysql.connector.connect(host="localhost",
user="root",passwd="root" ,database=“College")
mycursor=mydb.cursor()
mycursor.execute("create table student(rollno
int(3) primary key,name varchar(20),age int(2))")
How to change table structure/(add,edit,remove
colum of a table) at run time

• To modify the structure of the table we just have


to use alter table query. Below program will add
a column mark in the student table.
• import mysql.connector
mydb=mysql.connector.connect(host="localhost
",user="root",passwd="root" ,database="college
") mycursor=mydb.cursor()
mycursor.execute("alter table student add
(marks int(3))") mycursor.execute("desc
student") for x in mycursor: print(x)
THANKS

You might also like