DEV Community

Lakshmi Pritha Nadesan
Lakshmi Pritha Nadesan

Posted on

Day 32 - OOPS, CSV, matplotlib

Object Oriented Programming(OOPS):
OOPS stands for Object-Oriented Programming System, which is a programming paradigm based on the concept of objects.

Class:

A blueprint or template for creating objects.
Class represent logical entities.

Object:

Object represents class.
Object is representative of class.
Objects is instance of class.
Objects represent real-world entities or real time entities.
Objects has states and behavior.

we cannot create object without class.But class can be present without objects.

Example with Bike:

The Bike class defines what a bike is and what it can do.
States like brand, color, and speed describe the bike.
Behavior like start, accelerate, and stop define actions a bike can perform.
Activa and Scooter are objects of the Bike class.
Each object represents a real bike with specific states (e.g., brand and color) and behaviors.

Here are some of the key reasons why we use OOP in Python:

  1. Code reuseability
  2. Maintainability

Example:


from PIL import Image
photo = Image.open("/home/prigo/Documents/Python_class/images.jpeg")
photo.show()
Enter fullscreen mode Exit fullscreen mode

Image description

CSV (Comma Separated Values):

CSV file represents a row, and each value within the row is separated by a comma.
CSV file look like Excel but Excel file open only in excel software.
CSV file is used all the operating system.

We can open the CSV file in the following two formats.

f =open("sample.txt", "r")

with open("sample.txt",’r’) as f:
Enter fullscreen mode Exit fullscreen mode

r-read
Opens the file for reading. File must exist.
w-write
Opens the file for writing. Creates a new file or overwrites an existing one.
rb-read binary
This is used to read binary files like images, videos, audio files, PDFs, or any non-text files.

Matplotlib:

Matplotlib is a powerful and widely used plotting library in Python that helps you create static, animated, and interactive visualizations.

Common Plot Types:

Line Plot:Good for showing trends over time.
Bar Chart:Useful for comparing discrete values.
Histogram:Shows the distribution of a dataset.
Scatter Plot:Shows the relationship between two variables.
Pie Chart:Useful for showing proportions of a whole.

Example for csv and matplotlib:
sales.csv
Years,Sales
2020,10000
2021,8000
2022,9500
2023,10500
2024,12000

import matplotlib.pyplot as plt
import csv

years = []
sales = []

with open("sales.csv","r") as f:
    reader = csv.reader(f)
    next(reader)
    for each_row in reader:
        years.append(int(each_row[0]))
        sales.append(int(each_row[1]))

print(years)
print(sales)

plt.figure(figsize =(7,5))
plt.plot(years, sales, color="r", label="Yearly Sales")
plt.xlabel('Years')
plt.ylabel("Sales")
plt.title("Last 5 Years Sales ")
plt.show()

Enter fullscreen mode Exit fullscreen mode

Output:

[2020, 2021, 2022, 2023, 2024]
[10000, 8000, 9500, 10500, 12000]

Enter fullscreen mode Exit fullscreen mode

Image description

The code we have provided opens a file abcd.txt in write mode ("w") and prints out various attributes related to the file object f.

f = open("abcd.txt","w")
print(type(f))
print(f.name)
print(f.mode)
print(f.readable())
print(f.writable())
print(f.closed)
Enter fullscreen mode Exit fullscreen mode

Output:

<class '_io.TextIOWrapper'>
abcd.txt
w
False
True
False

We are opening the file abcd.txt in write mode ("w"), writing two strings ("Friday" and "Saturday") to the file, and then closing the file.

f = open("abcd.txt","w")
f.write("Friday")
f.write("Saturday")
f.close()
Enter fullscreen mode Exit fullscreen mode

FridaySaturday

If abcd.txt already exists, its contents will be erased and replaced. If it doesn't exist, it will be created.

f = open("abcd.txt","w")
f.write("Friday")
f.write("Saturday")
f.close()

Enter fullscreen mode Exit fullscreen mode

sundaymonday

In append mode, the file is not overwritten; instead, new content is added to the end of the file. If the file doesn't exist, it will be created.

f = open("abcd.txt","a")
f.write("tuesday")
f.write("wednesday")
f.close()
Enter fullscreen mode Exit fullscreen mode

sundaymondaytuesdaywednesday

This opens the file abcd.txt in read mode ("r"). If the file doesn't exist, it will raise a FileNotFoundError.

f = open("abcd.txt","r")
data = f.read()
print(data)
f.close()
Enter fullscreen mode Exit fullscreen mode

sundaymondaytuesdaywednesdayjanfebmar

The read(5) method reads up to 5 characters, regardless of whether they are letters, spaces, or special characters.

f = open("abcd.txt","r")
data = f.read(5)
print(data)
f.close()
Enter fullscreen mode Exit fullscreen mode

sunda

The readline() method reads characters from the file until it encounters a newline character (\n) or reaches the end of the file.

f = open("abcd.txt","r")
data = f.readline()
print(data)
f.close()
Enter fullscreen mode Exit fullscreen mode

sundaymondaytuesdaywednesdayjanfebmar

f = open("abcd.txt","r")
data = f.readlines()
for every_line in data:
    print(every_line, end='')
f.close()
Enter fullscreen mode Exit fullscreen mode

Thursday
Friday
Saturday

Write a program to find no.of.lines, no.of words and no.of letters in the text file:

abcd.txt
Rose is a beautiful flower
Today is friday
Happy day

f = open("abcd.txt","r")
data = f.readlines()

word=0
letter=0

for each_line in data:
    line=len(data)
    words=each_line.split()
    word=word+len(words)
    for letters in words:
        letter=letter+len(letters)

print("No.of.lines:" ,line)
print("No.of.words:" ,word)
print("No.of.words:" ,letter)  


f.close()
Enter fullscreen mode Exit fullscreen mode

Output:
No.of.lines: 3
No.of.words: 10
No.of.words: 43

Write a program to check the given file is available or not:

import os
file_name = input("Enter file Name")
if os.path.isfile(file_name):
    print("File is present")   
    f = open(file_name, "r")
else:

    print("File is not present")
Enter fullscreen mode Exit fullscreen mode

Output:

Enter file Name/home/prigo/Documents/Python_class/abcd.txt
File is present

Top comments (0)