How to handle csv file using python

As i need to read something from a csv file using python.  I got something and put it here.

 

Module: csv

 

import csv

FILE_FULL_PATH = ‘D:\\Work\\script\\My Script\\Book1.csv‘

def f():
  with open(FILE_FULL_PATH,‘rb‘) as csvfile:
    for row in csv.reader(csvfile, delimiter=‘ ‘, quotechar=‘|‘):
    print type(row)
      for eachcol in row:
      print eachco

 

if __name__ == ‘__main__‘:
f()

 

 

OUTPUT:

C:\Python27\python.exe "D:/Work/script/My Script/my-test.py"
<type ‘list‘>  #here we know each row is read as a list
Col11,Col12,Col12,,COlE  #The col which is empty is stored as a empty in the list
<type ‘list‘>  
Col21,Col22,Col23,,

Process finished with exit code 0

 

 

how to write to csv file

def f_w():
  datas = []  #using list to store data
  with open(CONFIG_FILE_PATH,‘r‘) as f:       #read data from a txt file
  FIRST = True
  for line in f:
  if FIRST:
    datas.append(re.findall(‘[a-zA-Z]+‘,line))    #find word and retuan a list
    FIRST = False
  else:
    datas.append(re.findall(‘[a-zA-Z_ 0-9]+‘,line))   #as the data has _and 0-9
  for data in datas:
  print data,len(data)
  with open(FILE_FULL_PATH,‘wb‘) as csvfile:   #open file need to using b mode
    csvwriter = csv.writer(csvfile)     #converte to csvwriter
    for data in datas:                       #for each line in list write to csv
    csvwriter.writerow(data)

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。