Pythonはcsvファイルの書き込みと読み取り方法

3647 ワード

csvファイルへの書き込み
import csv
#      csv  ,           ,       test.csv  
f = open('/mnt/sdb/test.csv','w')
csv_writer = csv.writer(f)
#    
csv_writer.writerow(["Name","Label"])
#    (            for  
#   [image_name,labels]       ,  [0,4])
csv_writer.writerow([image_name,labels])
'''
Name   Label  
0       4     
'''
#  [image_name,labels]       , writerows      
#writer.writerows([[0,1,2],[4,5,6]])
'''
Name   Label  
0       4    
1       5    
2       6    
'''
#    
f.close()

csvファイルの読み込み
pandasを採用
import pandas as pd
fpath = "/mnt/sdb/test.csv"
df = pd.read_csv(fpath)
df = df[[ 'Name','Label']]

csvを採用
import csv
with open("test.csv","r") as csvfile:
    reader = csv.reader(csvfile)
    for line in reader:
        print line