Professional Documents
Culture Documents
An open CSV file is closed in the same manner as you close any other file, i.e., as
:
Dfile. close( )
Like text files, a CSV file will get created when opened in an
output file mode and if it does not exist already . That is, for The csv files are popular because of
the file modes, "uf', "w +", "a" "a+", the file will get created if these reasons : (i) Easier to create,
(ii) preferred export and import
it does not exist already and if it exists already , then the file
format for databases and spread-
modes uf' and w +"will overwr ite the existing file and the
11 11
sheets, (iii) capable of storing large
file mode II a" or II a +" will retain the content s of the file. amounts of data.
coMPUTER SCIENCE WIT
H PYTHON - XII
224
Role of Argument newline . of csv Files
5 •7 •1A in Op en ing ·fy an ad dit ion al ar gu me nt r
While opening csv files, in the ~e w ine , Which
op en (), yo u can1spe ci
of ne wl in e arg · t sp ec ify ho w w ld
. um en t is o
is an optional bu t 1m portan t ar·gument· Th erok'e g f'l ou
Python handle newlme . . wh ile wo r wi th csv 1 es.
characters m .
As csv files are text files, wh . . h so me of tra ns lat 10 ns oc cu r - su eh as
ile storing t em, h typ es
translation of end of lin e (EO rat ing sy ste m yo u are wo r k.
L) character as pe rt e oped' mg on etc.
Different operating system ff ren tly . Th e M S- DO S
s store EOL characte.rs 1 e .f t h
(including
Windows an d OS/2), UNIX, · h t ms all us e d1 f er en
an d Macmtos O pe rat mg sy s e
bl 5 4 1ists the EO L ch ara cte
c ara cte rs to
designate the en d of a line wi .
rs us ed by
thin a text file. Followmg ta
different operating systems. e ·
T able 5.4 EOL characters use
d in different operating system
s.
Symbol/Char MeaninJ! op era tim ! Syste m
CR [ \r ] Carriage Return Macintosh
LF [\il ] Line Feed UNIX
CR/LF [ \r \n ] Carriage Return/Line Feed MS-DOS, Windows, OS/2
NULL [\0 ] Null character Other OSs
No w wh at wo uld ha pp en if yo
u create a csv file on one op era
The EOL of one operating sys tin g sy ste m an d us e it on an
tem will no t be tre ate d as EO other.
if yo u ha ve given a.character L on an ot~ er op era tin g sy ste m.
, sa y'\ r', in yo ur text str ing Also,
an d if yo u try to op en an d rea (not as EO L but as pa rt of a
d from this file on a Ma cin tos tex t str ing )
OS will treat every '\ r' as EO h sy ste m, w ha t w ou ld h ap
L - yes, including the on e yo pen ? Mac
So wh at is the solution? We u ga ve as p art of the tex t str ing.
ll, the solution is pre tty sim
Just su pp res s the EOL transl ple. ~ ID@Qij
ation by specify thi rd arg um
en t
CJ
of op en () as ne wl ine =' ' (nu
ll string - no space in qu ote
If yo u specify the ne wl ine arg s). Additional opt ion al arg
um ent as
um en t while wr iti ng on to a new line = " (null string; no spa
file, it will create a csv file wi csv ce in
th no EOL translation an d yo between) wit h file open(
will be able to us e csv file in u ) will
normal wa y on an y platform ensure tha t no tra nsl ati on
of
Th at is, op en yo ur csv file as . end of
: line (EOL) cha rac ter takes
place.
.
Df1 l e = open( "st u . csv ", "w
", ne wl ine . . . - - - - null string · no sp
= ,,) · b
Or ' ace m etween
~ CSV file opened in write mode wit
h file handle
Fil el = open( "s tu . csv ", "r" as Dfi le (no EO L translation
)
, ne wl ine = '•) ~ cs
. . --- -- V_file opened in rea
. d mo de with file handle
Not only this IS useful for workm
g across different platfo as•Fil el (no EO L translation)
same platform for writing and
reading. yo u will be able to ~s 1.
wh en we talk ab ou t rea din g , It ~ also us efu l wh en yo u wo
from the csv files. Pr o rk on the
pprea ate the role of the newlin
Let us no w lea rn to wo rk wi
th csv module's gr am 5 .21 on wa rd .t ·11 e arg um en t
th d . . 1 b
5 . 7.2 Wn·t·1ng in · CSV F'I me o s to wn te / rea d s. WI e cle ar to yo u.
I es .
mt o CSV files.
Writing into csv files involv
es the conversion of th
an d th_en storing it in the for
m of csv file. For w r~ se ~
followmg three key pla ye rs da ta int o ~e wr ita ble de lim
functions2. ite d for m
g nto a cs v files, yo u no rm
2. Other than the above shown fun all y us e the
ctions, there are other full,C,ijol\J,.
scope of the syllabus, hence we •
shall not cover these;.,. this ,.,._ 0
.&.!.•
~t like
1.,.1.ld.JI er. Did:Writer() function but th
ese are beyon d the
Chapter 5 : FILE HANDLING
225
These are:
csv. writer()
returns a writer object which writes data into CSV file
<writero bject>.w riterow( )
writes one row of data onto the writer object
<writero bject>.w riterows ()
writes multiple rows of data onto the writer object
B~fore we ~roceed, it is importan t for you to understa nd the significance of the writer object.
Smee ~sv files a:e _delimited flat files and before writing onto them, the data must be in
csv-wntable-dehmited-form3 , it is importan t to convert the received user data into the form
approp:i ate fo_r the cs: files. This task is performed by the writer object. The data row written
to ~ wnter ~bJ~ct (written using writerow () or writerows() functions) gets converted to csv
writable dehm1ted form and then written on to the linked csv file on the disk.
Following figure 5.8 illustrates this process.
MEMORY
csv.writer object
Delimited
It converts the user data data
into csv writable form ,
i.e., delimited string form ~ - ~ - - _ _ , , ,
as per csv settings.
csv.writerow() is
used to write onto
the writer object CSV fil e on
storage disk
In the above statemen t, delimiter argumen t is not specified. When you skip the delimiter
argumen t, the default deli_miter character, ~hich _is . comma, is used for separ~~ g
characters. But if you specify a character with delimiter argumen t then the spec1f1ed
characte r is used as the delimiter, e.i,
stuwrite r = csv.wri ter(fh, delimit er=' I')
The above statemen t will create file with delimiter character as pipe symbol (' I').
3. It depends on something called dialect, which by default is set for producing excel format like csv files. It can
even _be
excel-tab where tab character is the delimiter. You can set the dialect using dialect argument but we shall only work with
the default dialect and hence won't use dialect argument here. For further details on dialect argument, you ma,, r!"fer
to the
Python's documentation.
226 COMPUTER SCIENCE WITH PYTHON _ XII
You only need to write into the writer object. Rest of the work it will do itself, i.e., converting the
data into delimited form and then writing it onto the linked csv file.
Let us now do it practically. Following program illustrates this process.
n 5.19
Write a program to create a CSV file to store student data (Rollno., Name, Marks). Obtain data from
user and Write 5 records into the file.
lr~ram
import csv
fh = open ( "Student . csv" , "w" ) #open file
stuwriter = csv. writer(fh)
stuwriter . wri terow ( [ ' Rollno ' , ' Name ' , ' Marks ' J ) #write header row
for i in range(S) : '----_ -
11
print( Student record", (i+l) )
• Column headings written
The samp le run of the above program is as sh b Py~hon data sequence written on the writer
0 b1ect using writerow()
own elow:
Student record 1
Student record 3
Enter rollno:U
Enter rollno:13 Student records
Enter name:Nistha
Enter name:Rustom Enter rollno:15
Enter marks:79
Enter marks:75
St udent record 2 Enter name:sadaf
Student record 4 Enter marks:as
Enter rollno:12
Enter rollno:l4
Enter name:Rudy
Enter marks: 89 Enter name:Gurjot
Enter marks: sg
Chapter 5 : FILE HANDLING
227
Now if you open the folder of your
. p Ython program, you will
· see that Python has created a file
·
by the name Student.csv
i l
• I Python work .
Share View
v8
v See, a CSV file ork p
,.. ( look at its Type)
*Quick, Name Type has got created.
LJ ::itut.aat UAI rile - - _, ., l(.tl
1111D1 r
uAT rile - - - -
♦ D1 .,I' ent
@ D, ;I ,. test
1 KB
~ test1 Python File 1 KB ..,
31 items
And if you open this file in Notepad or any other ASCII editor, it shows:
r, 5.20 The data of winners of four rounds of a competitive programming competition is given as :
J\
~
r
~
~
One row
CSVfile on fetch one row at 8 time of data
storage disk
- from ~•d ar object
using a loop
i One row
of data
Let us now learn to read from csv files. In order to read from a csv file 1 you need to do the
following :
The file being opened must already exist otherwise an exception will get raised. Your
code should be able to handle the exception i.e., through try .. except. (Alternatively you
can use the with statement as mentioned below.)
(iii) Create the reader object by using the syntax as shown below:
You may also specify a delimiter character other than a comma using the delimiter
argument, e.g.,
(iv) The reader object stores the parsed data in the form of iterable and thus you can fetch
from it row by row through a traditional for loop, one row at a time :
·...-=---=- Loop to fetch one row at a time in rec from the iterable
4t
for rec in stureader :
print (rec) # or do any other processing
All the above mentioned steps are best performed through with statement as the with
statement will also take care of any exception that may arise while opening/reading a file. Thus
you should process the csv file as per the following syntax, which combines all the above
mentioned steps :
Let us do it practically.
\
\
.. . :.
Following program is doing the same. r ' ,,r j"'l:;"\ ,"!"; ,,,-rjl...- :i.•. ... ••
r, 5.21 .1
You created the Ii e com
. Lhe previous prog ram as shown below.
presu!Lcsv tn
. tie and m.. - 0
lr~ram Write a program to rea d the records of this csv l L--' - ~
-0----:-:-:-:-:-:-:--:-;-::-;::-I
file fd;t FQnnat y;ew tie P
display them. Name, Points, Rank
th15
Note. Before we write the code for . Pro9 ram ' recall that the Shradha, 4500, 23 1
eated without Nishchay,4800,
given file created in
. the prevwu
· s program, . was er
() function. So Ali· ' 4500 ' 25 3
specifying the new/me 1 .
. argumen t ·n the fr/e open ) code before Adi,5100,14
have a look at the previous program's (program 5·20
starting with this program's code. ..,
import csv
11
With open ( compresult. csv , r 11 11 11
) as fh ··
creader = csv. reader( fh)
for rec in creader :
print(rec) Loop to fetch one row a t a .
time in rec from the iterable in creader
Compare the above output with the sample run of previous program (program 5.20). We never
entered empty rows. Then where have these empty rows come from? Any idea?
You guessed it right. We did not specify the newline argument in the file open() function while
creating/writing this csv file (compresult.csv, in this case) and thus EOL translation took place,
which
data resulted
was in the
internally rows after every record while reading. In fact, the above shown file
blankas:
stored
So what is the solution? You are right again©. We should have created the file with newline
argument set to null string (' ') so that no EOL translation COUid lake place.
Chapter 5 : FILE HANDLING
231
In fact, the above situation can be handled in two ways :
(i) M_eth~dl. _Create/write onto csv file with newline='' argument in open() function so
this situation would not arise. Programs 5.23(a) and (b) illustrate this solution.
(ii) Method2. To read from a file which is created with EOL translation (i.e., no newline
argument), open it with newline argument set to the EOL character of the OS where the
csv file was created. For instance, if you created the csv file on a Windows OS, open file
for reading with newline argument set as ' \ r \n' because the EOL on Windows is stored
as '\r\n', i.e., as :
Now the file will be read considering every '\r\n'
character as newlinej
open( <csvfilename>, <readmode>, newline= '\r\n' ) ◄
Recall that the table 5.4 lists EOL characters on various operating systems.
Program 5.22 handles this situation using method 2 listed here. Let us have a look at it.
r, 5.22 The csv file (compresult.csv) used in the previous program was created on Windows OS where the
I
r:gram
EOL character is '\r\n' . Modify the code of the previous program so that blank lines for every EOL
are not displayed.
impo rt csv
with open("compresu lt.csv", "r", newline= '\r\ n' ) as fh:
cr eader = csv . reader(fh) '
for rec in creader : Now the file will be read considering every '\r\n' character as
print (rec) end of line and not as a separate line
The output produced by above program is: The newline argument can be
specified in independent open()
[' Name ' , ' Points' , 'Rank'] statement as well as in the open()
[' shradha ', '4500', '23'] of with statement.
[' Ni shchay' , '4800' , '31' J
[' A1 i ', ' 4500', '25 ']
[' Adi ' , ' 5100' , '14']
12
og am import csv
_ This argument ensures that no EOL
...., -..- - - translation takes place
fh = open("Employee .csv", "w", newline= )
ewriter = csv.writer(fh)
empdata = [ • • •]
['Empno', 'Name','Designation, Salary ,
[1001, 'Trupti','Manager',56880],
COMPUTER SCIENCE WITH PYTHON - XII
232
[1002, 'Raziya', 'Manager', 55900 ],
[1003, 'Simran', 'Analyst',3 5000 ],
[1004, 'Silviya', 'Clerk',2s0°e],
[1005, 'Suj i', 'PR Officer' , 31000 ]
]
ewriter.writerows(empdata)
print( "Fiie successfully created")
fh.close()
The above program created a file as shown below :
Employee - Notepad 0 X
Eile .Edit FQrmat ':f__iew Help
Empno,Name,Designation,Salary ~
1001,Trupti,Manager,56000
1002,Raziya,Manager,55900
1003,Simran,Analyst,35000
1004,Silviya,Clerk,2500 0
1005,Suji,PR Officer,31000 "'
.,. ..
I'
Let us now read from the above created file. This time we need not specify the newline
argument as no EOL translation has taken place. Program 5.23(b) is doing the same.
r, 5 •23 (b) Write a )imgram t.o iftfild and display tl!w «:lD]l)(tg}1}ltf§@flE'riwp1l\;J-ye~~~<!:~e.ml iiro.l ~ p,~ic;n:is; 1)~1i1!1l.