1. 程式人生 > >使用python簡單地寫入CSV資料

使用python簡單地寫入CSV資料

import csv

def save_csv1():
    with open('data.csv', 'w') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['id', 'name', 'age'])
        writer.writerow(['10001', 'Mike', 20])
        writer.writerow(['10002', 'Bob', 22])
        writer.writerow(['10003', 'Jordan', 21])
        
# 修改間隔
def save_csv2(): with open('data.csv', 'w') as csvfile: writer = csv.writer(csvfile, delimiter='\t') writer.writerow(['id', 'name', 'age']) writer.writerow(['10001', 'Mike', 20]) writer.writerow(['10002', 'Bob', 22]) writer.writerow(['10003', 'Jordan', 21]) # 寫入多行
def save_csv3(): with open('data.csv', 'w') as csvfile: writer = csv.writer(csvfile) writer.writerow(['id', 'name', 'age']) writer.writerows([['10001', 'Mike', 20], ['10002', 'Bob', 22], ['10003', 'Jordan', 21]]) # 字典寫入 def save_csv4(): with open('data.csv', 'w') as csvfile: fieldnames =
['id', 'name', 'age'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerow({'id': '10001', 'name': 'Mike', 'age': 20}) writer.writerow({'id': '10002', 'name': 'Bob', 'age': 22}) writer.writerow({'id': '10003', 'name': 'Jordan', 'age': 21}) # 寫入中文 def save_csv5(): with open('data.csv', 'a', encoding='utf-8') as csvfile: fieldnames = ['id', 'name', 'age'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writerow({'id': '10005', 'name': '王偉', 'age': 22}) def load_csv(): with open('data.csv', 'r', encoding='utf-8') as csvfile: reader = csv.reader(csvfile) for row in reader: print(row) def load_csv_by_pandas(): import pandas as pd df = pd.read_csv('data.csv') print(df) def save_csv_by_pd(): import pandas as pd head = ["表頭1" , "表頭2" , "表頭3"] l = [[1, 2, 3],[4 ,5 ,6],[8, 7, 9]] df = pd.DataFrame (l , columns = head) df.to_csv("testfoo.csv" , encoding = "utf-8") df2 = pd.read_csv("testfoo.csv" , encoding = "utf-8") print (df2) if __name__ == "__main__": save_csv_by_pd()