1. 程式人生 > >Python處理csv檔案

Python處理csv檔案

import csv

'''
普通方式讀取csv檔案
'''
def read_csv():
    with open('example.csv', 'r') as file:
        reader = csv.reader(file) # 返回可迭代物件, 只可被遍歷一次
#         for row in list(reader): # 返回一個二維陣列
#             print(row)
        for row in reader: # 可使用.next獲取一行資料
            print(reader.line_num, row)

'''
以字典的形式讀取csv檔案
'''
def read_to_dict(): with open('example.csv', 'r') as file: reader = csv.DictReader(file) for row in reader: print(row) ''' 匯出csv資料 - Dict形式 ''' def export_with_Dict(): fieldName = ['name', 'age'] data = [ {'name': 'Mike', 'age': 12}, {'name'
: 'Jack', 'age': 13}, {'name': 'Bob', 'age': 14}, {'name': 'Tom', 'age': 15}, ] with open('example.csv', 'w', newline = '') as file: writer = csv.DictWriter(file, fieldnames = fieldName) writer.writeheader() for row in data: writer.
writerow(row) # 寫入多行 writer.writerrows(data) print('export success') ''' 匯出csv資料 - List形式 ''' def export_with_list(): data = [ ['name', 'age'], ['Mike', 12], ['Jack', 13], ['Jerry', 14], ] with open('exmplae.csv', 'w', newline = '') as file: writer = csv.writer(file) for row in data: writer.writerow(row) # 寫入多行 writer.writerows(data) if __name__ == '__main__': pass