import csv
# open the filewithopen('csvfile.csv','r')as csvfile:# create the object of csv.reader()
csv_file_reader = csv.reader(csvfile,delimiter=',')for row in csv_file_reader:print(row)
import csv
withopen('data.csv','r')as f:
reader = csv.reader(f)# loop through each row and print each valuefor row in reader:for e in row:print(e)withopen('data.csv','r')as f:# change the delimiter from the default comma to another delimiter
reader = csv.reader(f, delimiter="|")for row in reader:for e in row:print(e)
nums =[[1,2,3,4,5,6],[7,8,9,10,11,12]]withopen('numbers2.csv','w')as f:
writer = csv.writer(f)# write arrays as rows to CSV filefor row in nums:
writer.writerow(row)withopen('numbers2.csv','w')as f:
writer = csv.writer(f, delimiter="+")# write arrays as row to CSV file with + as the delimiter instead of commasfor row in nums:
writer.writerow(row)
withopen(r'c:dlFrameRecentSessions.csv')as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count =0for row in csv_reader:if line_count ==0:print(f'Column names are {", ".join(row)}')
line_count +=1else:print(f' {row[0]} works in the {row[1]} department, and was born in {row[2]}.')
line_count +=1print(f'Processed {line_count} lines.')
import csv
header =['name','area','country_code2','country_code3']
data =['Afghanistan',652090,'AF','AFG']withopen('countries.csv','w', encoding='UTF8', newline='')as f:
writer = csv.writer(f)# write the header
writer.writerow(header)# write the data
writer.writerow(data)
# importing Pandas libraryimport pandas as pd
pd.read_csv(filepath_or_buffer ="pokemon.csv")# makes the passed rows header
pd.read_csv("pokemon.csv", header =[1,2])# make the passed column as index instead of 0, 1, 2, 3....
pd.read_csv("pokemon.csv", index_col ='Type')# uses passed cols only for data frame
pd.read_csv("pokemon.csv", usecols =["Type"])# returns pandas series if there is only one column
pd.read_csv("pokemon.csv", usecols =["Type"],
squeeze =True)# skips the passed rows in new series
pd.read_csv("pokemon.csv",
skiprows =[1,2,3,4])