0% found this document useful (0 votes)
13 views15 pages

Unit5 CS

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 15

What is CSV?

CSV (Comma Separated Values) is a simple file format used to store tabular
data, such as a spreadsheet or database. A CSV file stores tabular data
(numbers and text) in plain text. Each line of the file is a data record. Each
record consists of one or more fields, separated by commas. The use of the
comma as a field separator is the source of the name for this file format.
For working CSV files in Python, there is an inbuilt module called csv.
Working with CSV files in Python
Below are some operations that we perform while working with CSV files
in Python
 Reading a CSV file
 Writing to a CSV file
 Writing a dictionary to a CSV file
 Storing email in CSV file
Reading a CSV file
Reading from a CSV file is done using the reader object. The CSV file is
opened as a text file with Python’s built-in open() function, which returns a file
object. In this example, we first open the CSV file in READ mode, file object is
converted to csv.reader object and further operation takes place. Code and
detailed explanation is given below.
 Python

# importing csv module

import csv

# csv file name

filename = "aapl.csv"

# initializing the titles and rows list

fields = []
rows = []

# reading csv file

with open(filename, 'r') as csvfile:

# creating a csv reader object

csvreader = csv.reader(csvfile)

# extracting field names through first row

fields = next(csvreader)

# extracting each data row one by one

for row in csvreader:

rows.append(row)

# get total number of rows

print("Total no. of rows: %d"%(csvreader.line_num))

# printing the field names

print('Field names are:' + ', '.join(field for field in fields))


# printing first 5 rows

print('\nFirst 5 rows are:\n')

for row in rows[:5]:

# parsing each column of a row

for col in row:

print("%10s"%col,end=" "),

print('\n')

Output:

The above example uses a CSV file aapl.csv which can be downloaded
from here.
Run this program with the aapl.csv file in the same directory.
 Let us try to understand this piece of code.
with open(filename, 'r') as csvfile:
csvreader = csv.reader(csvfile)
 Here, we first open the CSV file in READ mode. The file object is named
as csvfile. The file object is converted to csv.reader object. We save the
csv.reader object as csvreader.
fields = csvreader.next()
 csvreader is an iterable object. Hence, .next() method returns the current
row and advances the iterator to the next row. Since, the first row of our csv
file contains the headers (or field names), we save them in a list
called fields.
for row in csvreader:
rows.append(row)
 Now, we iterate through the remaining rows using a for loop. Each row is
appended to a list called rows. If you try to print each row, one can find that
a row is nothing but a list containing all the field values.
print("Total no. of rows: %d"%(csvreader.line_num))
 csvreader.line_num is nothing but a counter which returns the number of
rows that have been iterated.
Writing to a CSV file
To write to a CSV file, we first open the CSV file in WRITE mode. The file object
is converted to csv.writer object and further operations takes place. Code and
detailed explanation is given below.
 Python

# importing the csv module

import csv

# field names

fields = ['Name', 'Branch', 'Year', 'CGPA']

# data rows of csv file

rows = [ ['Nikhil', 'COE', '2', '9.0'],


['Sanchit', 'COE', '2', '9.1'],

['Aditya', 'IT', '2', '9.3'],

['Sagar', 'SE', '1', '9.5'],

['Prateek', 'MCE', '3', '7.8'],

['Sahil', 'EP', '2', '9.1']]

# name of csv file

filename = "university_records.csv"

# writing to csv file

with open(filename, 'w') as csvfile:

# creating a csv writer object

csvwriter = csv.writer(csvfile)

# writing the fields

csvwriter.writerow(fields)

# writing the data rows

csvwriter.writerows(rows)

Let us try to understand the above code in pieces.


 fields and rows have been already defined. fields is a list containing all the
field names. rows is a list of lists. Each row is a list containing the field
values of that row.
with open(filename, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
 Here, we first open the CSV file in WRITE mode. The file object is named
as csvfile. The file object is converted to csv.writer object. We save the
csv.writer object as csvwriter.
csvwriter.writerow(fields)
 Now we use writerow method to write the first row which is nothing but the
field names.
csvwriter.writerows(rows)
 We use writerows method to write multiple rows at once.
Writing a dictionary to a CSV file
To write a dictionary to a CSV file, the file object (csvfile) is converted to a
DictWriter object. Detailed example with explanation and code is given below.
 Python

# importing the csv module

import csv

# my data rows as dictionary objects

mydict =[{'branch': 'COE', 'cgpa': '9.0',

'name': 'Nikhil', 'year': '2'},

{'branch': 'COE', 'cgpa': '9.1',

'name': 'Sanchit', 'year': '2'},

{'branch': 'IT', 'cgpa': '9.3',

'name': 'Aditya', 'year': '2'},


{'branch': 'SE', 'cgpa': '9.5',

'name': 'Sagar', 'year': '1'},

{'branch': 'MCE', 'cgpa': '7.8',

'name': 'Prateek', 'year': '3'},

{'branch': 'EP', 'cgpa': '9.1',

'name': 'Sahil', 'year': '2'}]

# field names

fields = ['name', 'branch', 'year', 'cgpa']

# name of csv file

filename = "university_records.csv"

# writing to csv file

with open(filename, 'w') as csvfile:

# creating a csv dict writer object

writer = csv.DictWriter(csvfile, fieldnames = fields)

# writing headers (field names)


writer.writeheader()

# writing data rows

writer.writerows(mydict)

In this example, we write a dictionary mydict to a CSV file.


with open(filename, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames = fields)
 Here, the file object (csvfile) is converted to a DictWriter object. Here, we
specify the fieldnames as an argument.
writer.writeheader()
 writeheader method simply writes the first row of your csv file using the pre-
specified fieldnames.
writer.writerows(mydict)
 writerows method simply writes all the rows but in each row, it writes only
the values(not keys).
So, in the end, our CSV file looks like this:

csv file

Consider that a CSV file looks like this in plain text:


university record

 We notice that the delimiter is not a comma but a semi-colon. Also, the rows
are separated by two newlines instead of one. In such cases, we can specify
the delimiter and line terminator.

Python Stack and Queue


Data structure organizes the storage in computers so that we can easily access and
change data. Stacks and Queues are the earliest data structure defined in computer
science. A simple Python list can act as a queue and stack as well. A queue follows FIFO
rule (First In First Out) and used in programming for sorting. It is common for stacks and
queues to be implemented with an array or linked list.

Stack
A Stack is a data structure that follows the LIFO(Last In First Out) principle. To implement
a stack, we need two simple operations:

o push - It adds an element to the top of the stack.


o pop - It removes an element from the top of the stack.
Operations:

o Adding - It adds the items in the stack and increases the stack size. The addition takes
place at the top of the stack.
o Deletion - It consists of two conditions, first, if no element is present in the stack, then
underflow occurs in the stack, and second, if a stack contains some elements, then the
topmost element gets removed. It reduces the stack size.
o Traversing - It involves visiting each element of the stack.

Characteristics:
o Insertion order of the stack is preserved.
o Useful for parsing the operations.
o Duplicacy is allowed.

Code

1. # Code to demonstrate Implementation of


2. # stack using list
3. x = ["Python", "C", "Android"]
4. x.push("Java")
5. x.push("C++")
6. print(x)
7. print(x.pop())
8. print(x)
9. print(x.pop())
10. print(x)

Output:

['Python', 'C', 'Android', 'Java', 'C++']

['Python', 'C', 'Android', 'Java']


C++
['Python', 'C', 'Android']
java

Queue
A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends
hence we can easily add elements to the back and can remove elements from the front.

To implement a queue, we need two simple operations:

o enqueue - It adds an element to the end of the queue.


o dequeue - It removes the element from the beginning of the queue.
Operations on Queue

o Addition - It adds the element in a queue and takes place at the rear end, i.e., at the
back of the queue.
o Deletion - It consists of two conditions - If no element is present in the queue,
Underflow occurs in the queue, or if a stack contains some elements then element
present at the front gets deleted.
o Traversing - It involves to visit each element of the queue.

Characteristics
o Insertion order of the queue is preserved.
o Duplicacy is allowed.
o Useful for parsing CPU task operations.

Code
1. import queue
2. # Queue is created as an object 'L'
3. L = queue.Queue(maxsize=10)
4.
5. # Data is inserted in 'L' at the end using put()
6. L.put(9)
7. L.put(6)
8. L.put(7)
9. L.put(4)
10. # get() takes data from
11. # from the head
12. # of the Queue
13. print(L.get())
14. print(L.get())
15. print(L.get())
16. print(L.get())

Output:

9
6
7
4

1. Print pattern

**

***

****

n = int(input("Enter the number of rows"))


# Here, we are declaring an outer loop to handle number of rows

for i in range(0, n):

for j in range(0, i + 1):

# Here, we are declaring a for loop for printing stars

print("* ", end="")

print()

2. Print pattern

12

123

1234

rows = int(input("Enter the number of rows: "))

# Here, we are declaring the for loop that is used to print the number of rows

for i in range(1, rows+1):

# Here, we are declaring the for loop that is used to print the number of columns

for j in range(1, i + 1):

print(j, end=' ')

print("")

3. WAP to calculate GCD of two numbers using recursive function

def hcf(a, b):

if(b == 0):

return a

else:

return hcf(b, a % b)
a = 60

b = 48

# prints 12

print("The gcd of 60 and 48 is : ", end="")

print(hcf(60, 48))

4. Write a program that read a file line by line. Each line read from file is copied to another file with line
number specified at the beginning of the line.

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

f1=open("file1.txt", "w")

num=1

for line in f:

f1.write(str(num)+ ":"+ line)

num=num +1

f.close()

f1.close()

You might also like