Python CSV page: source code

From CMEE4K
Jump to navigation Jump to search

Example 1: General

# General example
def doIt(n):
    if n == 0:
        '''print ("abc") '''
        return "Good Bye"
    else:
        print ("n is ", n, "continue ...")
        return doIt(n-1)
print ("Hello")
print (doIt(3))
print ("fun fun")

Example 2: Factorial

# Example Factorial
def fact(n):
    if n == 0:
        return 1
    else:
        return n * fact(n-1)
print(fact(0))
print(fact(5))

Example 3: Python-let on key-value dictionary (code)

# python-let on key value dictionary
def display(dict):
   for key in dict:
        value = dict[key]
        print (key)
        print (value)
mDict = {}
mDict["color"] = "blue"
mDict["fruit"] = "apple"
mDict["pet"] = "dog"
display(mDict)

Example 4: Python-let on key-value dictionary (data)

strA = "1|2|3|4|5|66|7|8"
dataSet = {"tpo_eta": strA}
aa = strA.split("|")[3]
print(aa)
print(dataSet["tpo_eta"])
arrayA = dataSet["tpo_eta"].split("|")
print(arrayA)
print(arrayA[3])

Example 5: Import CSV Python module

# importing the csv module 
import csv 
  
# field names 
fields = ['student ID', 'Name', 'Branch', 'Year', 'CGPA'] 
  
# data rows of csv file 
rows = [ ['111', 'Nikhil', 'COE', '2', '9.0'], 
         ['222', 'Sanchit', 'COE', '2', '9.1'], 
         ['333', 'Aditya', 'IT', '2', '9.3'], 
         ['444', 'Sagar', 'SE', '1', '9.5'], 
         ['555', 'Prateek', 'MCE', '3', '7.8'], 
         ['666', 'Sahil', 'EP', '2', '9.1']] 
  
# name of csv file 
filename = "data.csv"
  
# writing to csv file 
with open(filename, 'w') as csvfile: 
    # creating a csv writer object 
    csvwriter = csv.writer(csvfile) 
      
    # writing the fields 
    csvwriter.writerow(fields) 
      
    # writing the data rows 
    csvwriter.writerows(rows)

Example 6: Read CSV file

import csv

delimiter = '|'
key = ""
value = ""
myDict = {}
with open('data.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        print(row)
        # print(row[0])
        # print(row[0],row[1],row[2],)
        key = row[0]
        value = row[1]+delimiter+row[2]+delimiter+row[3]
        myDict[key] = value
print (myDict)

Download pandas command

pip install pandas