首页 > 代码库 > How to handle csv file using python
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)
How to handle csv file using python