resources that were tied with the file and is done using Python close() method. f = open("sample.txt") # perform file operations f.close() . . .
CSV Module’s Reader Function You can read the contents of CSV file with the help of csv.reader() function. The reader function is designed to take each line of the file and make a list of all columns. Then, you just choose the column you want the variable data for. Using this function one can read data from csv files of different formats like quotes (" "), pipe (|) and comma (,).
The syntax for csv.reader() is 12th Computer Chapter - - Python and CSV Files csv.reader(fileobject,delimiter,fmtparams) where file object :- passes the path and the mode of the file delimiter :- an optional parameter containing the standard dilects like , | etc can be omitted fmtparams: optional parameter which help to override the default values of the dialects like skipinitialspace,quoting etc. Can be omitted CSV file - data with default delimiter comma (,) CSV file - data with Space at the beginning CSV file - data with quotes CSV file - data with custom Delimiters . . .
. CSV file with default delimiter comma (,) The following program read a file called “sample1.csv” with default delimiter comma (,) and print row by row. #importing csv import csv #opening the csv file which is in different location with read mode with open('c:\pyprg\sample1.csv', 'r', newline‘=’) as F: #other way to open the file is f= ('c:\pyprg\sample1.csv', 'r') reader = csv.reader(F) # printing each line of the Data row by row for row in reader: print(row) F.close() OUTPUT ['SNO', 'NAME', 'CITY'] ['12101', 'RAM', 'CHENNAI'] ['12102', 'LAVANYA', 'TIRUCHY'] ['12103', 'LAKSHMAN', 'MADURAI'] . .
. . . CSV files- data with Spaces at the beginning Consider the following file “sample2.csv” containing the following data when opened through notepad Topic1, Topic2, Topic3, one, two, three Example1, Example2, Example3 12th Computer Chapter - - The following program read the file through Python using “csv.reader()”.
import csv csv. ('myDialect',delimiter = ',',skipinitialspace=True) F=open('c:\pyprg\sample2.csv','r') reader = csv.reader(F, dialect='myDialect') for row in reader: