Ads by ProfitSence
Close

Working with csv files using python

Last Updated on Wednesday 5th Oct 2022

First of all, what is a CSV ?

  • CSV --> Comma Separated Values
  • It is a simple file format used to store tabular data, such as a spreadsheet/excel or database.
  • CSV is convenient way to export data to spreadsheets and databases as well as import or use it in other programs.

Working with csv with "," as delimiter

			
					import csv 
req_file="details.csv"

fo=open(req_file,"r")
content=csv.reader(fo,delimiter=",")
for each in content:
    print(each)

fo.close()

#OUTPUT
['KEYS', 'FrameWorks', 'Skill']
['1', 'Svelte', 'JavaScript']
['2', 'Django', 'Python']
['3', 'Raeact','JavaScript/JSX']

			
	

How to get header in a csv file

			
					import csv 
req_file="details.csv"

fo=open(req_file,"r")
content=csv.reader(fo,delimiter=",")
my_list=list(content)
print(f'The head is:n {my_list[0]}')

fo.close()

#OUTPUT
['KEYS', 'FrameWorks', 'Skill']

			
	

How to get the number of rows in a csv file

			
					import csv 
req_file="details.csv"

fo=open(req_file,"r")
content=csv.reader(fo,delimiter=",")
print('The number of rows are:', len(list(content))-1)

#OUTPUT
The number of rows are: 3

			
	

Creating csv file

			
					import csv
req_file="det.csv"

fo=open(req_file,'w',newline="")
csv_writer=csv.writer(fo,delimiter=",")

csv_writer.writerow(['KEYS', 'FrameWorks', 'Skill'])
csv_writer.writerow([1,"VueJS",'JavaScript'])
csv_writer.writerow([2,"Hugo",'GO'])

fo.close()