0% found this document useful (0 votes)
22 views16 pages

Unit - V (Python Programming)

The document discusses file handling in Python. It covers opening, reading, writing, and closing files as well as deleting files and folders. It also discusses creating and interacting with databases and tables in MySQL using Python.

Uploaded by

aniltimes13
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)
22 views16 pages

Unit - V (Python Programming)

The document discusses file handling in Python. It covers opening, reading, writing, and closing files as well as deleting files and folders. It also discusses creating and interacting with databases and tables in MySQL using Python.

Uploaded by

aniltimes13
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
You are on page 1/ 16

>>>File Handling

The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
The code above is the same as:
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error.
Python File Open
Open a File on the Server
Assume we have the following file, located in the same folder as Python:
demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
To open the file, use the built-in open() function.
The open() function returns a file object, which has a read() method for reading the content of the
file:
Example Output:
f Hello! Welcome to
= open("demofile.txt", "r") demofile.txt
print(f.read()) This file is for
testing purposes.
Good Luck!

If the file is located in a different location, you will have to specify the file path, like this:

Example Output:
Open a file on a different location:
Welcome to this text
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read()) file!
This file is located in
a folder named
"myfiles", on the D
drive.
Good Luck!

**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 1


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("demofile.txt", "r")
print(f.read(5))
Output:
Hello
Read Lines
You can return one line by using the readline() method:
Example
Read one line of the file:
f = open("demofile.txt", "r")
print(f.readline())
Output:
Hello! Welcome to demofile.txt
By calling readline() two times, you can read the two first lines:
Example
Read two lines of the file:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
Output:
Hello! Welcome to demofile.txt
This file is for testing purposes.
By looping through the lines of the file, you can read the whole file, line by line:
Example
Loop through the file line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)
Output:
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
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("demofile.txt", "r")
print(f.readline())
f.close()
Output:
Hello! Welcome to demofile.txt
Python File Write
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

**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 2


Example
Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
Output:
Hello! Welcome to demofile2.txt
This file is for testing purposes.
Good Luck!Now the file has more content!
Example
Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the overwriting:
f = open("demofile3.txt", "r")
print(f.read())
Woops! I have deleted the content!
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 "myfile.txt":
f = open("myfile.txt", "x")
Result: a new empty file is created!
Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")
Python Delete File
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
Example
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
Check if File exist:
To avoid getting an error, you might want to check if the file exists before you try to delete it:
Example
Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 3
Delete Folder
To delete an entire folder, use the os.rmdir() method:
Example
Remove the folder "myfolder":
import os
os.rmdir("myfolder")
Note: You can only remove empty folders.

>>>Python MySQL Create Database


Creating a Database
To create a database in MySQL, use the "CREATE DATABASE" statement:
Example
create a database named "mydatabase":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")

If the above code was executed with no errors, you have successfully created a database.
Check if Database Exists
You can check if a database exist by listing all databases in your system by using the "SHOW
DATABASES" statement:
Example
Return a list of your system's databases:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
Output:
('information_scheme',)
('mydatabase',)
('performance_schema',)
('sys',)

Or you can try to access the database when making the connection:
Example
Try connecting to the database "mydatabase":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",

**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 4


user="yourusername",
password="yourpassword",
database="mydatabase"
)

If the database does not exist, you will get an error.


>>>Python MySQL Create Table
Creating a Table
To create a table in MySQL, use the "CREATE TABLE" statement.
Make sure you define the name of the database when you create the connection
Example
Create a table named "customers":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address
VARCHAR(255))")
If the above code was executed with no errors, you have now successfully created a table.
Check if Table Exists
You can check if a table exists by listing all tables in your database with the "SHOW TABLES"
statement:
Example
Return a list of your system's databases:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
Output:
('customers',)

>>>Python MySQL Insert Into Table


Insert Into Table
To fill a table in MySQL, use the "INSERT INTO" statement.
Example
Insert a record in the "customers" table:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 5
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
Output:
1 record inserted.
Insert Multiple Rows
To insert multiple rows into a table, use the executemany() method.
The second parameter of the executemany() method is a list of tuples, containing the data you
want to insert:
Example
Fill the "customers" table with data:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "was inserted.")
Output:
13 record was inserted.
Get Inserted ID
You can get the id of the row you just inserted by asking the cursor object.
Note: If you insert more than one row, the id of the last inserted row is returned.
**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 6
Example
Insert one row, and return the ID:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("Michelle", "Blue Village")
mycursor.execute(sql, val)
mydb.commit()
print("1 record inserted, ID:", mycursor.lastrowid)
Output:
1 record inserted, ID: 15
>>>Python MySQL Select From
Select From a Table
To select from a table in MySQL, use the "SELECT" statement:
Example
Select all records from the "customers" table, and display the result:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output:
(1, 'John', 'Highway 21')
(2, 'Peter', 'Lowstreet 27')
(3, 'Amy', 'Apple st 652')
(4, 'Hannah', 'Mountain 21')
(5, 'Michael', 'Valley 345')
(6, 'Sandy', 'Ocean blvd 2')
(7, 'Betty', 'Green Grass 1')
(8, 'Richard', 'Sky st 331')
(9, 'Susan', 'One way 98')
(10, 'Vicky', 'Yellow Garden 2')
(11, 'Ben', 'Park Lane 38')
(12, 'William', 'Central st 954')
(13, 'Chuck', 'Main Road 989')
(14, 'Viola', 'Sideway 1633')
(15, 'Michelle', 'Blue Village')
**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 7
Selecting Columns
To select only some of the columns in a table, use the "SELECT" statement followed by the
column name(s):
Example
Select only the name and address columns:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT name, address FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output:
('John', 'Highway 21')
('Peter', 'Lowstreet 27')
('Amy', 'Apple st 652')
('Hannah', 'Mountain 21')
('Michael', 'Valley 345')
('Sandy', 'Ocean blvd 2')
('Betty', 'Green Grass 1')
('Richard', 'Sky st 331')
('Susan', 'One way 98')
('Vicky', 'Yellow Garden 2')
('Ben', 'Park Lane 38')
('William', 'Central st 954')
('Chuck', 'Main Road 989')
('Viola', 'Sideway 1633')
('Michelle', 'Blue Village')
Using the fetchone() Method
If you are only interested in one row, you can use the fetchone() method.
The fetchone() method will return the first row of the result:
Example
Fetch only one row:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchone()
print(myresult)
Output:
**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 8
(1, 'John', 'Highway 21')
>>>Python MySQL Delete From By
Delete Record
You can delete records from an existing table by using the "DELETE FROM" statement:
Example
Delete any record where the address is "Mountain 21":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE address = 'Mountain 21'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
Output:
1 record(s) deleted
>>>Python MySQL Drop Table
Delete a Table
You can delete an existing table by using the "DROP TABLE" statement:
Example
Delete the table "customers":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DROP TABLE customers"
mycursor.execute(sql)
Drop Only if Exist
If the table you want to delete is already deleted, or for any other reason does not exist, you can
use the IF EXISTS keyword to avoid getting an error.
Example
Delete the table "customers" if it exists:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()

**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 9


sql = "DROP TABLE IF EXISTS customers"
mycursor.execute(sql)
>>>Python MySQL Update Table
Update Table
You can update existing records in a table by using the "UPDATE" statement:
Example
Overwrite the address column from "Valley 345" to "Canyon 123":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
Output:
1 record(s) affected

>>>What is NumPy?
 NumPy is a Python library used for working with arrays.
 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.
 Numpy is a python package for scientific computing that provides high-performance
multidimensional arrays objects. This library is widely used for numerical analysis,
matrix computations, and mathematical operations.

>>>NumPy String Functions


NumPy contains the following functions for the operations on the arrays of dtype string.
S Function Description
N

1 add() It is used to concatenate the corresponding array elements (strings).

2 multiply() It returns the multiple copies of the specified string, i.e., if a string 'hello' is multiplied by 3
then, a string 'hello hello' is returned.

3 center() It returns the copy of the string where the original string is centered with the left and right
padding filled with the specified number of fill characters.

4 capitalize( It returns a copy of the original string in which the first letter of the original string is
) converted to the Upper Case.

**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 10


5 title() It returns the title cased version of the string, i.e., the first letter of each word of the string is
converted into the upper case.
>>>NumPy Mathematical Functions
Numpy contains a large number of mathematical functions which can be used to perform various
mathematical operations. The mathematical functions include trigonometric functions, arithmetic
functions, and functions for handling complex numbers. Let's discuss the mathematical
functions.
The numpy.ceil() function
This function is used to return the ceiling value of the array values which is the smallest integer
value greater than the array element. Consider the following example.
Example
import numpy as np
arr = np.array([12.202, 90.23120, 123.020, 23.202])
print(np.ceil(arr))
Output:
[ 13. 91. 124. 24.]
The numpy.floor() function
This function is used to return the floor value of the input data which is the largest integer not
greater than the input value. Consider the following example.
Example
import numpy as np
arr = np.array([12.202, 90.23120, 123.020, 23.202])
print(np.floor(arr))
Output:
[ 12. 90. 123. 23.]
>>>Numpy statistical functions
Numpy provides various statistical functions which are used to perform some statistical data
analysis. In this section of the tutorial, we will discuss the statistical functions provided by the
numpy.
Finding the minimum and maximum elements from the array
The numpy.amin() and numpy.amax() functions are used to find the minimum and maximum of
the array elements along the specified axis respectively.
Example
import numpy as np
a = np.array([[2,10,20],[80,43,31],[22,43,10]])
print("The original array:\n")
print(a)
print("\nThe minimum element among the array:",np.amin(a))
print("The maximum element among the array:",np.amax(a))
print("\nThe minimum element among the rows of array",np.amin(a,0))
print("The maximum element among the rows of array",np.amax(a,0))
print("\nThe minimum element among the columns of array",np.amin(a,1))
print("The maximum element among the columns of array",np.amax(a,1))
Output:
69.3M
1.2K
Difference between JDK, JRE, and JVM
The original array:
[[ 2 10 20]
**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 11
[80 43 31]
[22 43 10]]
The minimum element among the array: 2
The maximum element among the array: 80
The minimum element among the rows of array [ 2 10 10]
The maximum element among the rows of array [80 43 31]
The minimum element among the columns of array [ 2 31 10]
The maximum element among the columns of array [20 80 43]
numpy.ptp() function
The name of the function numpy.ptp() is derived from the name peak-to-peak. It is used to return
the range of values along an axis. Consider the following example.
Example
import numpy as np
a = np.array([[2,10,20],[80,43,31],[22,43,10]])
print("Original array:\n",a)
print("\nptp value along axis 1:",np.ptp(a,1))
print("ptp value along axis 0:",np.ptp(a,0))
Output:
Original array:
[[ 2 10 20]
[80 43 31]
[22 43 10]]
ptp value along axis 1: [18 49 33]
ptp value along axis 0: [78 33 21]
>>>What is Matplotlib?
 Matplotlib is a low level graph plotting library in python that serves as a visualization
utility.
 Matplotlib was created by John D. Hunter.
 Matplotlib is open source and we can use it freely.
 Matplotlib is mostly written in python, a few segments are written in C, Objective-C and
Javascript for Platform compatibility.
Matplotlib Pyplot
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under
the plt alias:
import matplotlib.pyplot as plt
Now the Pyplot package can be referred to as plt.
Example
Draw a line in a diagram from position (0,0) to position (6,250):
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints)
plt.show()
Result:

**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 12


Matplotlib Plotting
Plotting x and y points
The plot() function is used to draw points (markers) in a diagram.
By default, the plot() function draws a line from point to point.
The function takes parameters for specifying points in the diagram.
Parameter 1 is an array containing the points on the x-axis.
Parameter 2 is an array containing the points on the y-axis.
If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays [1, 8] and [3, 10] to the
plot function.
Example
Draw a line in a diagram from position (1, 3) to position (8, 10):
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints)
plt.show()
Result:

Plotting Without Line


To plot only the markers, you can use shortcut string notation parameter 'o', which means 'rings'.
Example
Draw two points in the diagram, one at position (1, 3) and one in position (8, 10):
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])

**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 13


plt.plot(xpoints, ypoints, 'o')
plt.show()
Result:

Matplotlib Markers
Markers
You can use the keyword argument marker to emphasize each point with a specified marker:
Example
Mark each point with a circle:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, marker = 'o')
plt.show()
Result:

Matplotlib Line
Linestyle
You can use the keyword argument linestyle, or shorter ls, to change the style of the plotted line:
Example
Use a dotted line:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, linestyle = 'dotted')
plt.show()
Result:
**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 14
Histogram
A histogram is a graph showing frequency distributions.
It is a graph showing the number of observations within each given interval.
Example: Say you ask for the height of 250 people, you might end up with a histogram like this:

You can read from the histogram that there are approximately:
2 people from 140 to 145cm
5 people from 145 to 150cm
15 people from 151 to 156cm
31 people from 157 to 162cm
46 people from 163 to 168cm
53 people from 168 to 173cm
45 people from 173 to 178cm
28 people from 179 to 184cm
21 people from 185 to 190cm
4 people from 190 to 195cm
Creating Pie Charts
With Pyplot, you can use the pie() function to draw pie charts:
Example
A simple pie chart:
import matplotlib.pyplot as plt
import numpy as np
y = np.array([35, 25, 25, 15])
plt.pie(y)
plt.show()
Result:
**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 15
Creating Bars
With Pyplot, you can use the bar() function to draw bar graphs:
Example
Draw 4 bars:
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x,y)
plt.show()
Result:

**UNIT-V PYTHON PROGRAMMING*** **S.PRABHAVATHI**** Page 16

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy