본문 바로가기
study/python

파이썬 데이터베이스 - csv, json 파일 형식 다루기

by kuah_ 2022. 6. 17.

 

 

 

 

CSV 파일

- 데이터를 콤마로 구분하고, 각 튜플을 엔터로 구분하여 열 단위 자료를 작성한 텍스트 파일

- 테이블 구조와 유사하여 테이블로 호출할 수 있음

- 하단 예제와 파일(Let's python 교재에서 발췌)

bmi.csv
0.27MB

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import pandas as pd # pandas는 R과 비슷한 기능을 파이썬에서 구현할 수 있게 해줌
import pymysql
 
# (1) csv 파일 로드
bmi = pd.read_csv("data/bmi.csv")
print("bmi.info() : ", bmi.info()) # None
 
 
# (2) 각 컬럼 추출
height = bmi['height']
weight = bmi['weight']
label = bmi['label']
 
config = {                  
    'host' : '127.0.0.1',  
    'user' : 'root',        
    'passwd' : 'password',  
    'database' : 'db',  
    'port' : 3306,          
    'charset' : 'utf8',      
    'use_unicode' : True    
    }
 
try : 
  conn = pymysql.connect(**config)
  cursor = conn.cursor()
 
  # (3) table 조회
  cursor.execute("show tables")
  tables = cursor.fetchall()
 
  # (4) 스위칭 기법
  sw = False
  for table in tables :
    if table[0== 'bmi_tab' : # table 튜플의 첫번째 요소를 검사. 
      # 모든 테이블 이름을 검사하여 bmi_tab이 있는지 판단
      sw = True # table 있는 경우 swapping
  
  # (5) table 생성
  if not sw :
    print('테이블 없음'# table 없으면 생성
    sql = """create table bmi_tab(
            height int not null,
            weight int not null,
            label varchar(15) not null)
          """
    cursor.execute(sql)
 
  # (6) 레코드 조회
  cursor.execute("select * from bmi_tab")
  rows = cursor.fetchall()
  if rows : # (7) 레코드 있는 경우 : 레코드 조회
    for row in rows :
      print(f"{row[0]}    {row[1]}    {row[2]}")
    print("전체 레코드 수 : "len(rows))
  else : # (8) 레코드 없는 경우 : 레코드 추가
    print("100 레코드 추가")
    for i in range(100) :
      h = height[i]
      w = weight[i]
      lab = label[i]
      cursor.execute(f"insert into bmi_tab values({h}, {w}, '{lab}')")
      conn.commit()
except Exception as e :
  print("db error : ", e)
finally : 
  cursor.close()
  conn.close()
cs

 

 

 

JSON

- {'키' : '값'} 으로 이루어진 딕셔너리 모음으로 구성된 형식의 파일

- {}은 테이블의 레코드 한줄에 대응

- 하단 예제와 파일(Let's python 교재에서 발췌)

labels.json
0.01MB

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import json
 
# 1. json file decoding
file = open("data/labels.json", mode='r', encoding="utf-8")
# decoding : json 문자열 -> dict 유형으로 받음
# mode = 'r'은 읽기용으로 호출하는 
 
lines = json.load(file)
print(type(lines)) # <class 'list'>
print(len(lines)) # 30
print(type(lines[0])) # <class 'dict'>
 
# row 단위 출력
cnt = 0
for line in lines : # 모든 라인 출력 (총 30개). 리스트 내에 있는 딕셔너리를 받아온 것
    cnt += 1 
    print(cnt, '->', line) # json 파일 내부에 있는 데이터 전체를 딕셔너리 하나당 한라인으로 받아온 것
 
file.close() # open한거 닫아줘야 함
# 안해주면 프로세스가 종료되지 않고 읽기방식 소유권을 계속 가지고 있기 때문에 곤란
# 파일에 변동을 주는 것이라 큰 문제는 없음. 프로그램 종료되면 os가 소유권 다시 가져감
 
# 2. DataFrame 생성
import pandas as pd
df = pd.DataFrame(lines) # 데이터 프레임 = 테이블 형태의 데이터 구조. 스키마 출력됨.
print('df.info()---->\n',df.info()) 
'''
<class 'pandas.core.frame.DataFrame'> 
RangeIndex: 30 entries, 0 to 29
Data columns (total 5 columns):
id         30 non-null int64 -> int
url        30 non-null object -> varchar()
name       30 non-null object -> varchar()
color      30 non-null object -> varchar()
default    30 non-null bool -> str -> varchar()
'''
print('df.head()---->\n',df.head()) # 상위 5줄 출력. 인수 넣으면 줄 개수 지정 가능
 
# 3. db table 생성 -> 레코드 추가
import pymysql
config = {
    'host' : '127.0.0.1',
    'user' : 'root',
    'password' : 'root1234',
    'database' : 'test_db',
    'port' : 3306,
    'charset':'utf8',
    'use_unicode' : True}
 
try :
    conn = pymysql.connect(**config)
    cursor = conn.cursor()
 
    # 레코드 조회
    cursor.execute("select * from labels")
    rows = cursor.fetchall()
    if rows :
        print('labels 레코드 조회"---->\n',"labels 레코드 조회")
        for row in rows :
            print(row)
 
        print("전체 레코드 수 :"len(rows))
    else :
        print('labels 레코드 삽입"---->\n',"labels 레코드 삽입")
        for i in range(30) :
            uid = df.id[i] # df['column'] or df.column
            url = df.url[i]
            name = df.name[i]
            color = df.color[i]
            de = str(df.default[i]) # bool -> str
            sql = f"insert into labels values({uid},'{url}','{name}','{color}','{de}')"
            cursor.execute(sql)
            conn.commit() # db 반영
except Exception as e:
    print("db error : ", e)
finally:
    cursor.close()
    conn.close()
 
cs

 

 

 

 

댓글