Python CSV

phillip yoon·2021년 6월 25일
0

CSV


💡 Code

import csv

# 예제1
with open('./resource/test1.csv', 'r') as f:
    read_ = csv.reader(f)
    # next(reader) Header Skip
    # 객체 확인
    print(read_)
    # 타입 확인
    print(type(read_))
    # 속성 확인
    print(dir(read_))  # __iter__
    print()
    for c in read_:
        # print(c)
        # 타입 확인(리스트)
        # print(type(c))
        # list to str
        print(' : '.join(c))

with open('./resource/test2.csv', 'r') as f:
    read_2= csv.reader(f, delimiter='|')

    for c in read_2:
        print(c)

with open('./resource/test1.csv', 'r') as f:
    read_3 = csv.DictReader(f)
    print(read_3)
    print(type(read_3))
    print(dir(read_3))
    print()

    for c in read_3:
        for k,v in c.items():
            print(k,v)
        print('----------------')

w = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15],[16,17,18],[19,20,21]]
with open('./resource/write1.csv', 'w',encoding='utf-8') as f:
    print(dir(csv))
    wt = csv.writer(f)
    # dir 확인
    # print(dir(wt))
    # 타입 확인
    print(type(wt))
    for v in w:
        wt.writerow(v)
with open('./resource/write2.csv', 'w',encoding='utf-8') as f:
    fields = ['One', 'Two', 'Three']
    # Dic Writer
    wt = csv.DictWriter(f,fieldnames=fields)
    # Header Write
    wt.writeheader()

    for v in w:
        wt.writerow({'One': v[0], 'Two': v[1],'Three':v[2]})
profile
세상이 더 나아지기를 바라는 마음으로 개발에 임하고 있습니다.

0개의 댓글