码迷,mamicode.com
首页 > 编程语言 > 详细

How to handle csv file using python

时间:2014-11-27 12:39:12      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:ar   sp   for   on   bs   ad   ef   as   line   

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)

How to handle csv file using python

标签:ar   sp   for   on   bs   ad   ef   as   line   

原文地址:http://www.cnblogs.com/leon-zhu/p/4125846.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!