Python

[python] CSV FILE

SangRok Jung 2022. 9. 1. 22:51
반응형

 

CSV FILE


Comma-Separated Values의 약자

각 라인의 컬럼들이 콤마로 분리된 텍스트 파일 포맷이다.

 

 

 

 

 

 

 

CSV FILE 읽기


▶ os.listdir()

해당 주소의 파일들을 확인한다.

 

 

 

▶ os.path.isfile()

해당 주소의 파일이 있는지 참 거짓의 여부를 확인한다.

 

 

 

▶ encoding error시 대처

encoding 값을 utf8, utf16, utf32, cp949로 변경한다.

 

 

 

 

import csv
import os
import os.path

a = os.listdir("./encore_python/엔코아 파이썬 csv 실습 예제들/")
print(a)

file = "./encore_python/엔코아 파이썬 csv 실습 예제들/2021_seoul_day_temp.csv"
print(os.path.isfile(file))

# 인코딩 에러시 : utf8, utf16, utf32, cp949
with open("./encore_python/엔코아 파이썬 csv 실습 예제들/2021_seoul_day_temp.csv", "r", encoding="cp949") as f :
    line = f.readlines()
    line = line[7:-1].copy()
    for i in line :
        print(i.strip())

 

 

 

▷ 해당 파일에서 날짜에 맞는 정보 추출하기

 

※ endswith(끝나는 문자, option : 시작점, option : 끝나는점)

문자열이 특정문자로 끝나는지 참 거짓 여부를 반환한다.

 

with open("./encore_python/엔코아 파이썬 csv 실습 예제들/2021_seoul_day_temp.csv", "r", encoding="cp949") as f :
    line = f.readlines()
    line = line[7:-1].copy()
    for i in line :
        temp = i.split(",")
        date = temp[0].split("-")
        
        if temp[0].endswith("09-01") :
            print(f"{date[0]}년 {date[1]}월 {date[2]}일 서울의 평균기온은 {temp[2]}℃, 최저기온은{temp[3]}℃, 최고기온은{temp[4]}℃ 입니다.")

# 2021년 09월 01일 서울의 평균기온은 21.4℃, 최저기온은18.5℃, 최고기온은23.9℃ 입니다.

 

 

 

 

 

 

▷ 해당 파일에서 입력한 월의 온도를 10개씩 출력하면서 평균 온도를 뽑아내기

with open("./encore_python/엔코아 파이썬 csv 실습 예제들/2021_seoul_day_temp.csv", "r", encoding="cp949") as f :
    line = f.readlines()
    line = line[8:-1].copy()
    
    month = input("월을 입력하세요(ex : 01 ~ 12) : ")
    
    temp = []
    total = 0
    for i in line :
        if i.split(",")[0].endswith(month, 0, 7) :
            temp.append(float(i.split(",")[2]))
    total = sum(temp)

    z = 1
    while True :
        if z == len(temp) :
            break
        if z % 10 == 0:
            print("{0:^5}".format(temp[z-1]))
            z += 1
            continue
        print("{0:^5}".format(temp[z-1]), end = " ")
        z += 1

    print(f"\n%s월의 평균 기온 : %.2f" % (month, round(total/len(temp), 2)))
    
# 월을 입력하세요(ex : 01 ~ 12) : 02
#  5.0  -5.6  -3.2  -3.6   1.4   6.8   3.6  -3.1  -0.9   3.4 
#  5.5   6.5   7.6   9.5   1.2  -5.1  -8.3  -5.8   1.6   8.8 
# 10.8   7.8   0.0   2.9   4.2   8.2   9.5  
# 02월의 평균 기온 : 2.73

 

 

▷ 병원의 이름을 입력하여 병원의 주소 출력하기

with open("./encore_python/엔코아 파이썬 csv 실습 예제들/pharm_20226.csv", "r") as f :
    pharm = f.readlines()
    pharm_new = []
    name = input("병원을 입력하세요 : ")
    for i in pharm[1:] : 
        info = i.split(',')
        
        if info[1] == name :
            addr = info[-5]
            print(f"{name}의 주소 : {addr}")
            
# 병원을 입력하세요 : 독산종로약국
# 독산종로약국의 주소 : 서울특별시 금천구 독산로 360 (독산동)

 

 

 

 

▷ 건물이름과 도시 이름으로 병원의 정보 추출하기.

with open("./encore_python/엔코아 파이썬 csv 실습 예제들/pharm_20226.csv", "r") as f :
    pharm = f.readlines()
    pharm_new = []
    name = input("건물명 : ")
    region = input("시도명 : ")
    
    data = f" {region}내 {name} 건물 현황 "
    print("{0:*^30}\n{1:*^40}".format(data, "*"))
    
    for i in pharm[1:] : 
        info = i.split(',')
        name = info[1] 
        tel = info[-4]
        open_day = info[-3]
        
        if '"' in i :
            addr = i.split('"')[1]
        else : 
            addr = info[-5]
    
        if region in i and name in i : 
            print(f"약   국 : {name}\n주   소 : {addr}\n전화번호 : {tel}\n개업일자 : {open_day}")
            print("{0:-^40}".format("-"))
            
            
# 건물명 : 로얄스포츠
# 시도명 : 수지
# ****** 수지내 로얄스포츠 건물 현황 *******
# ****************************************
# 약   국 : 베델약국
# 주   소 : 경기도 용인시 수지구 문인로 59 107호 (풍덕천동, 삼익상가)
# 전화번호 : 031-276-0050
# 개업일자 : 2003.3.22
# ----------------------------------------
# 약   국 : 예쁜약국
# 주   소 : 경기도 용인시 수지구 신봉2로 2 센트럴500 223호 (신봉동)
# 전화번호 : 031-893-0750
# 개업일자 : 2018.4.30
# ----------------------------------------
# 약   국 : 희망약국
# 주   소 : 경기도 용인시 수지구 풍덕천로 119 118호 (풍덕천동, 로얄스포츠센터)
# 전화번호 : 031-264-4288
# 개업일자 : 2017.2.16
# ----------------------------------------

 

 

 

 

▶ 지역, 년도를 입력받아 설립원수 그래프, 수치 출력하기.

with open("./encore_python/엔코아 파이썬 csv 실습 예제들/pharm_20226.csv", "r") as f :
    pharm = f.readlines()
    pharm_new = []
    region = input("도시를 입력하세요 : ")
    start = int(input("시작 년도 : "))
    end = int(input("끝 년도 : "))
    graph = []
    
    for i in range(start, end+1) :
        graph.append({i : 0})
        
    
    data = f"{region}의 {start}부터 {end}까지의 개원 현황"
    print("{0:*^30}\n{1:*^40}".format(data, "*"))
    
    for i in pharm[1:] : 
        info = i.split(',')
        
        # 주소정립
        if '"' in i :
            addr = i.split('"')[1]
        else : 
            addr = info[-5]
        
        # 주소 확인
        if region in addr : 
            # 설립일 유무 확인
            if info[-3].split(".")[0] == "" :
                continue
            op_year = int(info[-3].split(".")[0])

            for y in range(len(graph)) : 
                for key, value in graph[y].items() :
                    if key == op_year :
                        graph[y][key] += 1
    
    # 그래프로 출력하기
    for i in range(len(graph)) :
        for key, value in graph[i].items() :
            print(f"{key} {'.' * int(value)}")
    
    # 숫자로 출력하기
    for i in range(len(graph)) :
        for key, value in graph[i].items() :
            print(f"{key} : {value}")

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

기존 데이터를 새롭게 저장


▶ 기존의 데이터를 읽어온뒤 형식화를 진행한다.

그 다음 구문에서 읽어오는 함수와 라인들을 제거 한 뒤 print()했던 구문들을 write로 변경해줘야한다.

with open("./encore_python/엔코아 파이썬 csv 실습 예제들/2021_seoul_day_temp.csv", "r", encoding="cp949") as f :
    line = f.readlines()
    line2 = line[7:8].copy()
    line = line[8:-1].copy()
    line3 = line2[0].split(",")

    print("{0:^11}|{1:^7}|{2:^8}|{3:^7}|".format(line3[0].strip(), line3[3].strip(), line3[4].strip(), "일교차"))
    
    for i in line :
        temp = i.split(",")
        date = temp[0].split("-")
        temp_range = float(temp[4]) - float(temp[3])
        print("{0:^12}|{1:^9}|{2:^9}|{3:^9}| ".format(temp[0], temp[3], temp[4].strip(), round(temp_range, 2)))

 

 

 

 

▶ 메모장 출력

with open("./encore_python/엔코아 파이썬 csv 실습 예제들/2021_seoul_day_temp2.csv", "w", encoding="cp949") as f :


    f.write("{0:^11}|{1:^7}|{2:^8}|{3:^7}|\n".format(line3[0].strip(), line3[3].strip(), line3[4].strip(), "일교차"))
    f.write("-"*40 + "\n")
    for i in line :
        temp = i.split(",")
        date = temp[0].split("-")
        temp_range = float(temp[4]) - float(temp[3])
        f.write("{0:^12}|{1:^9}|{2:^9}|{3:^9}|\n".format(temp[0], temp[3], temp[4].strip(), round(temp_range, 2)))

# 2021년 09월 01일 서울의 평균기온은 21.4℃, 최저기온은18.5℃, 최고기온은23.9℃ 입니다.

 

 

 

 

 

 

▶ 엑셀 출력(기본 출력)

,를 기준으로 나눈다.

with open("./encore_python/엔코아 파이썬 csv 실습 예제들/2021_seoul_day_temp3.csv", "w", encoding="cp949") as f :

    f.write("{0},{1},{2},{3}\n".format(line3[0].strip(), line3[3].strip(), line3[4].strip(), "일교차"))

    for i in line :
        temp = i.split(",")
        date = temp[0].split("-")
        temp_range = float(temp[4]) - float(temp[3])
        f.write("{0},{1},{2},{3}\n".format(temp[0], temp[3], temp[4].strip(), round(temp_range, 2)))

# 2021년 09월 01일 서울의 평균기온은 21.4℃, 최저기온은18.5℃, 최고기온은23.9℃ 입니다.

반응형

'Python' 카테고리의 다른 글

[python] 예외처리  (0) 2022.09.06
[python] Class  (0) 2022.09.03
[python] 파일 읽고 쓰기, 이름 바꾸기  (0) 2022.08.31
[python] for, if문 축약  (0) 2022.08.31
[python] function  (0) 2022.08.30