📖 generic · 12th TN - English Medium · COMPUTER SCIENCE · Page 230question

PYTHON AND CSV FILES · Part 8

Chapter 2: 3 · COMPUTER SCIENCE

print(row) F.close() OUTPUT ['Topic1', 'Topic2', 'Topic3'] ['one', 'two', 'three'] ['Example1', 'Example2', 'Example3'] As you can see in “sample2.csv” there are spaces after the delimiter due to which the output is also displayed with spaces. These whitespaces can be removed, by registering new dialects using csv. () class of csv module. A dialect describes the format of the csv file that is to be read.

In dialects the parameter “skipinitialspace” is used for removing whitespaces after the delimiter. By default “skipinitialspace” has a value false Note The following program reads “sample2.csv” file, which contains spaces after the delimiter. import csv csv. ('myDialect',delimiter = ',',skipinitialspace=True) F=open('c:\pyprg\sample2.csv','r') reader = csv.reader(F, dialect='myDialect') for row in reader: print(row) F.close() OUTPUT ['Topic1', 'Topic2', 'Topic3'] ['one', 'two', 'three'] ['Example1', 'Example2', 'Example3'] 12th Computer Chapter - - Python and CSV Files A dialect is a class of csv module which helps to define parameters for reading and writing CSV.

It allows you to create, store, and re-use various formatting parameters for your data. Note . . .

. CSV File-Data With Quotes You can read the csv file with quotes, by registering new dialects using csv. () class of csv module. Here, we have quotes.csv file with following data.

SNO,Quotes , "The secret to getting ahead is getting started." , "Excellence is a continuous process and not an accident." , "Work hard dream big never give up and believe yourself." , "Failure is the opportunity to begin again more intelligently." , "The successful warrior is the average man, with laser-like focus." The following Program read “quotes.csv” file, where delimiter is comma (,) but the quotes are within quotes (“ “). import csv csv. ('myDialect',delimiter = ',',skipinitialspace=True) f=open('c:\pyprg\quotes.csv','r') reader = csv.reader(f, dialect='myDialect') for row in reader: print(row) OUTPUT ['SNO', 'Quotes'] [' ', 'The secret to getting ahead is getting started.'] [' ', 'Excellence is a continuous process and not an accident.'] [' ', 'Work hard dream big never give up and believe yourself.'] [' ', 'Failure is the opportunity to begin again more intelligently.'] [' ', 'The successful warrior is the average man, with laser-like focus. '] In the above program, register a dialect with name myDialect.

Related topics

Have a question about this topic?

Get an AI answer grounded in your actual textbook — with the exact page reference.

Ask AI about this topic →