0% found this document useful (0 votes)
32 views2 pages

CSV 40

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views2 pages

CSV 40

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Python Data Processing and Encoding:

CSV (Comma Separated Values/Data) files to store data that are in tabular format
into plain text & each line is treated as a data record in the file.

Define Delimiter:
It is a sequence of one or more characters used to specify the boundary between
separate.

Example:
A delimiter is the comma character, or Space, or Gap or Colon etc.. a CSV file in
Notepad, Microsoft Excel, OpenOffice Calc, and Google Docs.

Syntax: CSV formated text..!!


fname,lname,age,salary
nancy,davolio,33,$30000
erin,borakova,28,$25250
tony,raphael,35,$28700

In PYTHON Environment we can able to work with csv files, we can use built-in
module is called CSV.
1. Open the file on required mode
2. Create the csv file represented object
3. Read or write or update the data

Syntax:
import csv

CSV Functions
1 csv.reader
2 csv.writer

EXAMPLE:Writing data in CSV file (Creating CSV File)


import csv
try:
with open("MyFile.csv",mode='w',encoding='utf-8') as FP:
a=csv.writer(FP,delimiter=',')
data=[['STOCK','SALES','PRICE'],
['100','90','90$'],
['300','100','100$'],
['100','200','200$']]
a.writerows(data)
print("CSVFileCreatedSuccessfully")
except IOError:
print("SorryCSVFileUnableTOCreate")
print("ServerWriteProtected")
finally:
print("FinallyBlockSuccess")

EXAMPLE:Appending data in CSV file..!!


import csv
try:
with open("BigData.csv",mode='a',encoding='utf-8') as FP:
a=csv.writer(FP,delimiter=',')
data=[['10','9','9$'],
['0','0','0$'],
['10','2','2$']]
a.writerows(data)
print("CSVFileAppendSuccessfully")
except IOError:
print("SorryCSVFileUnableTOAppend")
print("ServerWriteProtected")
finally:
print("FinallyBlockSuccess")

EXAMPLE: Reading CSV File Without Builtin Methods..!!


try:
with open("BigData.csv",mode='r',encoding='utf-8') as FP:
for data in FP:
print(data)
print("CSVFileReadSuccessfully")
except IOError:
print("SorryCSVFileUnableToAppend")
print("ServerWriteProtected")
finally:
print("FinallyBlockSuccess")

Example:Reading CSV File


import csv
with open("MyFile.csv",'r') as FP:
a=csv.reader(FP)
data=[]
for row in a:
if len(row)!=0:
data=data+[row]
print(data)

#without using csv module


path="MyFile.csv"
lines=[line for line in open(path)]
print(lines[0])

You might also like