Unit5 CS
Unit5 CS
Unit5 CS
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
import csv
filename = "aapl.csv"
fields = []
rows = []
csvreader = csv.reader(csvfile)
fields = next(csvreader)
rows.append(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
import csv
# field names
filename = "university_records.csv"
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)
import csv
# field names
filename = "university_records.csv"
writer.writerows(mydict)
csv file
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.
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 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
Output:
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.
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
**
***
****
print()
2. Print pattern
12
123
1234
# Here, we are declaring the for loop that is used to print the number of rows
# Here, we are declaring the for loop that is used to print the number of columns
print("")
if(b == 0):
return a
else:
return hcf(b, a % b)
a = 60
b = 48
# prints 12
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:
num=num +1
f.close()
f1.close()