<์˜ˆ์ œ ์ถœ์ฒ˜> 

https://wikidocs.net/22803

 

2) map, filter

์•ž์„œ ๋ฐฐ์šด ์ œ๋„ˆ๋ ˆ์ดํ„ฐ(`generator`)๋Š” ์ดํ„ฐ๋ ˆ์ดํ„ฐ(`iterator`) ์ž…๋‹ˆ๋‹ค. ๋‹ค๋งŒ ์ œ๋„ˆ๋ ˆ์ดํ„ฐ ํ‘œํ˜„์‹ ๋˜๋Š” `yield`ํ‚ค์›Œ๋“œ๋ฅผ ํ†ตํ•ด ์ƒ์„ฑํ•œ ์ดํ„ฐ๋ ˆ์ดํ„ฐ๋Š” ๊ตฌ๋ถ„์„ ...

wikidocs.net

 

 

์‚ฌ์šฉ๋ฒ•์ด ์ต์ˆ™์น˜ ์•Š์•„ ํ•ญ์ƒ ์ฐพ์•„๋ณด๋Š” map, filterํ•จ์ˆ˜๋ฅผ ํ™•์‹คํžˆ ์ •๋ฆฌํ•ด ๋†“๋Š”๋‹ค. 


map(์ ์šฉ์‹œํ‚ฌ ํ•จ์ˆ˜, ์ ์šฉํ•  ์š”์†Œ๋“ค) 

: ๋ฐ˜๋ณต๊ฐ€๋Šฅํ•œ iterable ๊ฐ์ฒด๋ฅผ ๋ฐ›์•„์„œ ๊ฐ ์š”์†Œ์— ํ•จ์ˆ˜๋ฅผ ์ ์šฉํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ 

 

#1. for๋ฌธ ์‚ฌ์šฉ

def add_1(n): 
    return n + 1

target = [1, 2, 3, 4, 5]
result = []

for value in target: 
    result.append(add_1(value))
    
print(result)

[2, 3, 4, 5, 6]

 

#2. mapํ•จ์ˆ˜ ์‚ฌ์šฉ

# map ํ•จ์ˆ˜ ์‚ฌ์šฉ 
def add_1(n): 
    return n + 1

target = [1, 2, 3, 4, 5]

result = map(add_1, target)

print(result)  # ์ถœ๋ ฅ๊ฒฐ๊ณผ: iterator -> nextํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ ํ™•์ธ ๊ฐ€๋Šฅ 
print(list(result))  # list ํƒ€์ž…์œผ๋กœ ํ˜•๋ณ€ํ™˜ ํ•˜์—ฌ ํ™•์ธ ๊ฐ€๋Šฅ

<map object at 0x000001B7457EF3C8>

[2, 3, 4, 5, 6]

 

#3. mapํ•จ์ˆ˜ + lambda ์‚ฌ์šฉ

# map + lambda: add_1 ๊ณผ ๊ฐ™์€ ํ•จ์ˆ˜๊ฐ€ ์žฌ์‚ฌ์šฉ ๋ชฉ์ ์ด ์—†๋‹ค๋ฉด lambda ํ•จ์ˆ˜ ์‚ฌ์šฉ
target = [1, 2, 3, 4, 5]

result = map(lambda x: x + 1, target)

print(list(result))

[2, 3, 4, 5, 6]

 

# ์ถ”๊ฐ€ ์˜ˆ์ œ: ๋ชจ๋“  ์š”์†Œ๋“ค์„ str ํƒ€์ž…์œผ๋กœ ๋ณ€๊ฒฝ 
target = [1, 2, 3, 4, 5]
list(map(str, target))

['1', '2', '3', '4', '5']


filter(์ ์šฉ์‹œํ‚ฌ ํ•จ์ˆ˜, ์ ์šฉํ•  ์š”์†Œ๋“ค) 

: ํŠน์ • ์กฐ๊ฑด์œผ๋กœ ๊ฑธ๋Ÿฌ์„œ ๊ฑธ๋Ÿฌ์ง„ ์š”์†Œ๋“ค๋กœ iterator ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด์„œ ๋ฆฌํ„ด 

#1. for๋ฌธ ์‚ฌ์šฉ

target = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = []

def is_even(n):
    return True if n % 2 == 0 else False 

for value in target: 
    if is_even(value): 
        result.append(value)
        
print(result)

 

#2. filter ํ•จ์ˆ˜ ์‚ฌ์šฉ

[2, 4, 6, 8, 10]

# filter ํ•จ์ˆ˜ ์‚ฌ์šฉ 
target = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def is_even(n): 
    return True if n % 2 == 0 else False

result = filter(is_even, target)

print(list(result))

[2, 4, 6, 8, 10]

 

#3. filter ํ•จ์ˆ˜ + lambda ์‚ฌ์šฉ

# filter + lambda
target = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = filter(lambda x: x%2==0, target)

print(list(result))

[2, 4, 6, 8, 10]

 

 

์‘์šฉ: Map + Filter ์˜ˆ์ œ

## target๋ฆฌ์ŠคํŠธ์˜ ๋ชจ๋“  ์š”์†Œ๋“ค์— 1์„ ๋”ํ•˜๊ณ  ํ™€์ˆ˜๋งŒ return
target = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list(filter(lambda x: x%2!=0, map(lambda x: x+1, target)))

[3, 5, 7, 9, 11]

 

์ฝ”๋“œ - ํŒจ์บ  ์ˆ˜์—… ์ฝ”๋“œ ์ฐธ๊ณ  (ํŒจ์บ  ์ˆ˜์—… ์ •๋ฆฌ)

 

 

<์ด์ „ ๊ธ€>

https://silvercoding.tistory.com/46

 

[python ๊ธฐ์ดˆ] 14. SQLITE ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์—ฐ๋™ (2) - ํ…Œ์ด๋ธ” ์กฐํšŒ

์ฝ”๋“œ - ํŒจ์บ  ์ˆ˜์—… ์ฝ”๋“œ ์ฐธ๊ณ  (ํŒจ์บ  ์ˆ˜์—… ์ •๋ฆฌ) <์ด์ „ ๊ธ€> https://silvercoding.tistory.com/45 https://silvercoding.tistory.com/44 https://silvercoding.tistory.com/43 https://silvercoding.tistory.com/42..

silvercoding.tistory.com

 

- sqlite3 import 

import sqlite3

 

 

- DB ์—ฐ๊ฒฐ (์ƒ์„ฑ) / (ํŒŒ์ผ) 

conn = sqlite3.connect('./resource/database.db')

 

 

- Cursor ์—ฐ๊ฒฐ 

c = conn.cursor()

 

 

- ์ปค๋ฐ‹

conn.commit()

์ด๋ฒˆ์—” ์˜คํ† ์ปค๋ฐ‹ ์„ค์ •์„ ํ•˜์ง€ ์•Š์„ ๊ฒƒ์ด๋ฏ€๋กœ ์ฝ”๋“œ์— ๊ฐ€์žฅ ๋งˆ์ง€๋ง‰์—๋Š” ์ปค๋ฐ‹์„ ์„ ์–ธํ•ด ๋†“์•„์•ผ ํ•œ๋‹ค. ์ด ์œ„์— ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜์ž. 

 

 

- ๋ฐ์ดํ„ฐ ์ˆ˜์ • 

(1) ๋ฐฉ๋ฒ• 1 : ํŠœํ”Œ 

c.execute("UPDATE users SET username = ? WHERE id = ?", ('niceman', 2))

id = 2 ์ธ username์„ niceman์œผ๋กœ ๋ฐ”๊พธ๋ผ๋Š” ๋œป์˜ ์ฝ”๋“œ์ด๋‹ค.

 

 

(2) ๋ฐฉ๋ฒ• 2 : ๋”•์…”๋„ˆ๋ฆฌ 

c.execute("UPDATE users SET username = :name WHERE id = :id", {'name': 'goodgirl', 'id': 5})

๋”•์…”๋„ˆ๋ฆฌ๋กœ key๋ฅผ ์—ฐ๊ฒฐํ•˜์—ฌ ์ˆ˜์ •ํ•  ์ˆ˜๋„ ์žˆ๋‹ค. 

 

 

(3) ๋ฐฉ๋ฒ• 3 : format

c.execute("UPDATE users SET username = '%s' WHERE id ='%s'" % ('badboy', 3))

% ๋ฅผ ์ด์šฉํ•˜์—ฌ ์—ฐ๊ฒฐํ•ด ์ค„ ์ˆ˜๋„ ์žˆ๋‹ค. 

 

 

* ์ค‘๊ฐ„ ๋ฐ์ดํ„ฐ ํ™•์ธ 1

for user in c.execute("SELECT * FROM users"):
    print(user)

 (1, 'Kim', 'silver@naver.com', '010-0000-0000', 'kim.com', '2021-08-03 13:28:23') 
 (2, 'niceman', 'Park@daum.net', '010-1111-1111', 'Park.com', '2021-08-03 13:28:23') 
 (3, 'badboy', 'Lee@naver.com', '010-2222-2222', 'Lee.com', '2021-08-03 13:28:23') 
 (4, 'Cho', 'Cho@daum.net', '010-3333-3333', 'Cho.com', '2021-08-03 13:28:23') 
 (5, 'goodgirl', 'Yoo@google.com', '010-4444-4444', 'Yoo.net', '2021-08-03 13:28:23') 

์ด๋ ‡๊ฒŒ ๋ฐ์ดํ„ฐ ์ˆœํšŒ๋ฅผ ํ†ตํ•ด ๋ฐ”๋€ ๊ฒƒ์„ ํ™•์ธ ํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

 

 

- ๋ฐ์ดํ„ฐ ์‚ญ์ œ 

(1) Row Delete 

# ๋ฐฉ๋ฒ• 1
c.execute("DELETE FROM users WHERE id = ?", (2,))

# ๋ฐฉ๋ฒ• 2 
c.execute("DELETE FROM users WHERE id = :id", {'id' : 5})

# ๋ฐฉ๋ฒ• 3 
c.execute("DELETE FROM users WHERE id = '%s'" % 4)

์‚ญ์ œ๋„ ๊ฐ™์€ 3๊ฐ€์ง€์˜ ๋ฐฉ๋ฒ•์œผ๋กœ ์›ํ•˜๋Š” ํ–‰์„ ์„ ํƒํ•˜์—ฌ ์‚ญ์ œํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

 

* ์ค‘๊ฐ„ ๋ฐ์ดํ„ฐ ํ™•์ธ 2 

for user in c.execute("SELECT * FROM users"):
    print(user)

 (1, 'Kim', 'silver@naver.com', '010-0000-0000', 'kim.com', '2021-08-03 13:28:23')    
 (3, 'badboy', 'Lee@naver.com', '010-2222-2222', 'Lee.com', '2021-08-03 13:28:23')   

 

 

(2) ํ…Œ์ด๋ธ” ์ „์ฒด ๋ฐ์ดํ„ฐ ์‚ญ์ œ 

print("users db deleted : ", conn.execute('DELETE FROM users').rowcount, " rows")

 users db deleted :  2  rows 

๋ชจ๋‘ ์‚ญ์ œ๋˜์—ˆ๋‹ค!

 

 

- ์ปค๋ฐ‹ & ์ ‘์† ํ•ด์ œ 

# ์ปค๋ฐ‹
conn.commit()

# ์ ‘์† ํ•ด์ œ 
conn.close()

์ปค๋ฐ‹์€ ๊ณ„์† ์„ ์–ธ์ด ๋˜์–ด ์žˆ์–ด์•ผ ํ•˜๊ณ , with๋ฌธ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด ์ ‘์†ํ•ด์ œ๋ฅผ ๊ผญ ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค. 

 

 

 

์ฝ”๋“œ - ํŒจ์บ  ์ˆ˜์—… ์ฝ”๋“œ ์ฐธ๊ณ  (ํŒจ์บ  ์ˆ˜์—… ์ •๋ฆฌ)

 

 

<์ด์ „ ๊ธ€>

https://silvercoding.tistory.com/45

 

[python ๊ธฐ์ดˆ] 13. SQLITE ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์—ฐ๋™ (1) - ํ…Œ์ด๋ธ” ์ƒ์„ฑ ๋ฐ ์‚ฝ์ž… ์‚ญ์ œ

์ฝ”๋“œ - ํŒจ์บ  ์ˆ˜์—… ์ฝ”๋“œ ์ฐธ๊ณ  (ํŒจ์บ  ์ˆ˜์—… ์ •๋ฆฌ) <์ด์ „ ๊ธ€> https://silvercoding.tistory.com/44 https://silvercoding.tistory.com/43 https://silvercoding.tistory.com/42 https://silvercoding.tistory.com/41..

silvercoding.tistory.com

 

* sqlite3 import 

import sqlite3

 

 

* DB ํŒŒ์ผ ์กฐํšŒ (์—†์œผ๋ฉด ์ƒˆ๋กœ ์ƒ์„ฑ) 

conn = sqlite3.connect('./resource/database.db') # ๋ณธ์ธ DB ๊ฒฝ๋กœ

 

 

* ์ปค์„œ ๋ฐ”์ธ๋”ฉ

c = conn.cursor()

 

 

* ํ…Œ์ด๋ธ” ์กฐํšŒ 

(1) ์ „์ฒด ๋ฐ์ดํ„ฐ ์กฐํšŒ 

c.execute('SELECT * FROM users')

์ด๋ฅผ ์‹คํ–‰ํ•˜๋ฉด ์•„๋ฌด์ผ๋„ ์ผ์–ด๋‚˜์ง€ ์•Š๋Š”๋‹ค. ์ด์ œ ์ด ์ƒํƒœ์—์„œ ์ปค์„œ ์œ„์น˜๋ฅผ ๋ณ€๊ฒฝํ•ด๊ฐ€๋ฉฐ ๋ฐ์ดํ„ฐ๋ฅผ ์กฐํšŒํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

 

 

(2) ์ปค์„œ ์œ„์น˜ ๋ณ€๊ฒฝ 

- 1๊ฐœ ๋กœ์šฐ ์„ ํƒ 

print('One -> \n', c.fetchone())

 One -> (1, 'Kim', 'silver@naver.com', '010-0000-0000', 'kim.com', '2021-08-03 13:28:23') 

fetchone()์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ฐ์ดํ„ฐ ํ•œ๊ฐœ๋ฅผ ์„ ํƒํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

- ์ง€์ • ๋กœ์šฐ ์„ ํƒ 

print('Three -> \n', c.fetchmany(size=3))

 Three -> [(2, 'Park', 'Park@daum.net', '010-1111-1111', 'Park.com', '2021-08-03 13:28:23'), 
(3, 'Lee', 'Lee@naver.com', '010-2222-2222', 'Lee.com', '2021-08-03 13:28:23'), (4, 
'Cho', 'Cho@daum.net', '010-3333-3333', 'Cho.com', '2021-08-03 13:28:23')] 

fetchmany()์˜ ์ธ์ž์— size ๊ฐœ์ˆ˜๋ฅผ ์ •ํ•ด์ฃผ๋ฉด ์ปค์„œ์˜ ํ˜„์žฌ ์œ„์น˜๋ถ€ํ„ฐ size๊ฐœ์ˆ˜ ๋งŒํผ์„ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค. 

 

 

- ์ „์ฒด ๋กœ์šฐ ์„ ํƒ 

print('All -> \n', c.fetchall())

 All -> [(5, 'Yoo', 'Yoo@google.com', '010-4444-4444', 'Yoo.net', '2021-08-03 13:28:23')]  

fetchall() ๋กœ ํ˜„์žฌ ์ปค์„œ์˜ ์œ„์น˜ ๋ถ€ํ„ฐ ๋ชจ๋“  ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค. 

print('All -> \n', c.fetchall())

 All -> [] 

5๊ฐœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋ชจ๋‘ ์กฐํšŒํ–ˆ์œผ๋ฏ€๋กœ ๋‚จ์€ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†๋‹ค! 

 

 

 

์ปค์„œ์˜ ์œ„์น˜๊ฐ€ ๋๋‚˜๋ฉด ์‹คํ–‰์ด ์•ˆ๋˜๋ฏ€๋กœ ์ฃผ์„์ฒ˜๋ฆฌ ํ•ด๊ฐ€๋ฉฐ ์‹คํ–‰ ํ•œ๋‹ค. 

(3) ์ˆœํšŒ 

- ์ˆœํšŒ 1 

rows = c.fetchall()
for row in rows: 
    print('retrieve1 > ', row)

 retrieve1 >  (1, 'Kim', 'silver@naver.com', '010-0000-0000', 'kim.com', '2021-08-03 13:28:23') 
 retrieve1 >  (2, 'Park', 'Park@daum.net', '010-1111-1111', 'Park.com', '2021-08-03 13:28:23') 
 retrieve1 >  (3, 'Lee', 'Lee@naver.com', '010-2222-2222', 'Lee.com', '2021-08-03 13:28:23') 
 retrieve1 >  (4, 'Cho', 'Cho@daum.net', '010-3333-3333', 'Cho.com', '2021-08-03 13:28:23') 
 retrieve1 >  (5, 'Yoo', 'Yoo@google.com', '010-4444-4444', 'Yoo.net', '2021-08-03 13:28:23') 

fetchall()์„ ์ด์šฉํ•˜์—ฌ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜๋ชฉ๋ฌธ์œผ๋กœ ์ˆœํšŒํ•ด ์ค„ ์ˆ˜ ์žˆ๋‹ค. 

 

 

- ์ˆœํšŒ 2 

for row in c.fetchall():
    print('retrieve2 > ', row)

 retrieve2 >  (1, 'Kim', 'silver@naver.com', '010-0000-0000', 'kim.com', '2021-08-03 13:28:23') 
 retrieve2 >  (2, 'Park', 'Park@daum.net', '010-1111-1111', 'Park.com', '2021-08-03 13:28:23') 
 retrieve2 >  (3, 'Lee', 'Lee@naver.com', '010-2222-2222', 'Lee.com', '2021-08-03 13:28:23') 
 retrieve2 >  (4, 'Cho', 'Cho@daum.net', '010-3333-3333', 'Cho.com', '2021-08-03 13:28:23') 
 retrieve2 >  (5, 'Yoo', 'Yoo@google.com', '010-4444-4444', 'Yoo.net', '2021-08-03 13:28:23') 

์ˆœํšŒ 1 ๊ณผ ๊ฐ™์ง€๋งŒ ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด ์ฃผ์ง€ ์•Š์•˜์„ ๋ฟ์ด๋‹ค. 

 

 

- ์ˆœํšŒ 3 : ๊ฐ€๋…์„ฑ์ด ๋–จ์–ด์งˆ ์ˆ˜ ์žˆ์Œ 

for row in c.execute('SELECT * FROM users ORDER BY id desc'):
    print('retrieve3 > ', row)

 retrieve3 >  (5, 'Yoo', 'Yoo@google.com', '010-4444-4444', 'Yoo.net', '2021-08-03 13:28:23') 
 retrieve3 >  (4, 'Cho', 'Cho@daum.net', '010-3333-3333', 'Cho.com', '2021-08-03 13:28:23') 
 retrieve3 >  (3, 'Lee', 'Lee@naver.com', '010-2222-2222', 'Lee.com', '2021-08-03 13:28:23') 
 retrieve3 >  (2, 'Park', 'Park@daum.net', '010-1111-1111', 'Park.com', '2021-08-03 13:28:23') 
 retrieve3 >  (1, 'Kim', 'silver@naver.com', '010-0000-0000', 'kim.com', '2021-08-03 13:28:23') 

fetchall()์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  execute๋กœ ๋ฐ”๋กœ ์ˆœํšŒํ•  ์ˆ˜๋„ ์žˆ๋‹ค. ์ด๋ฒˆ์—” ORDER BY ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ์„ ํ•˜์—ฌ ์ˆœํšŒํ–ˆ๋‹ค. 

 

 

 

(4) WHERE Retrieve 

- ๋ฐฉ๋ฒ• 1 : ํŠœํ”Œ

param1 = (3,)
c.execute('SELECT * FROM users WHERE id=?', param1)
print('param1', c.fetchone())
print('param1', c.fetchall()) # ๋ฐ์ดํ„ฐ ์—†์Œ

 param1 (3, 'Lee', 'Lee@naver.com', '010-2222-2222', 'Lee.com', '2021-08-03 13:28:23') 
 param1 [] 

WHERE์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ€์ ธ์˜ฌ ๋ฐ์ดํ„ฐ๋ฅผ ์„ ์ •ํ•  ์ˆ˜ ์žˆ๋‹ค. execute์˜ ์ธ์ž์— ํŠœํ”Œ๋กœ id๊ฐ’์„ ๋„ฃ์–ด์ฃผ๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค. 

 

 

- ๋ฐฉ๋ฒ• 2 : format 

param2 = 4
c.execute('SELECT * FROM users WHERE id="%s"' % param2)  # %s, %f, %d
print('param2', c.fetchone())
print('param2', c.fetchall()) # ๋ฐ์ดํ„ฐ ์—†์Œ

 param2 (4, 'Cho', 'Cho@daum.net', '010-3333-3333', 'Cho.com', '2021-08-03 13:28:23')

 param2 [] 

% ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ id๊ฐ’์„ ๋„ฃ์–ด์ค„ ์ˆ˜๋„ ์žˆ๋‹ค. 

 

 

- ๋ฐฉ๋ฒ• 3 : dictionary 

c.execute('SELECT * FROM users WHERE id=:Id', {"Id":5})
print('param3', c.fetchone())
print('param3', c.fetchall()) # ๋ฐ์ดํ„ฐ ์—†์Œ

 param3 (5, 'Yoo', 'Yoo@google.com', '010-4444-4444', 'Yoo.net', '2021-08-03 13:28:23') 
 param3 [] 

execute์˜ ์ธ์ž์— dictionary๋ฅผ ์ž‘์„ฑํ•˜๊ณ , key๊ฐ’์„ ์ผ์น˜์ง€์ผœ ์ค€๋‹ค. 

 

 

- ๋ฐฉ๋ฒ• 4 : IN & tuple

param4 = (3, 5)
c.execute('SELECT * FROM users WHERE id IN(?,?)', param4)
print('param4', c.fetchall())

 param4 [(3, 'Lee', 'Lee@naver.com', '010-2222-2222', 'Lee.com', '2021-08- 03 13:28:23'), (5, 'Yoo', 'Yoo@google.com',  '010-4444-4444', 'Yoo.net', '2021-08-03 13:28:23')] 

IN ๊ณผ ํŠœํ”Œ์„ ์‚ฌ์šฉํ•˜์—ฌ ์—ฌ๋Ÿฌ๊ฐœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค. 

 

 

- ๋ฐฉ๋ฒ• 5 : IN & format

c.execute('SELECT * FROM users WHERE id IN("%d", "%d")' % (3, 4))
print('param5', c.fetchall())

 param5 [(3, 'Lee', 'Lee@naver.com', '010-2222-2222', 'Lee.com', '2021-08-03 13:28:23'), (4, 'Cho', 'Cho@daum.net', '010-3333-3333', 'Cho.com', '2021-08-03 13:28:23')]  

IN๊ณผ % ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์—ฌ๋Ÿฌ๊ฐœ๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜๋„ ์žˆ๋‹ค. 

 

 

- ๋ฐฉ๋ฒ• 6 : OR & dictionary

c.execute('SELECT * FROM users WHERE id=:id1 OR id=:id2', {'id1':2, 'id2':5})
print('param6', c.fetchall())

 param6 [(2, 'Park', 'Park@daum.net', '010-1111-1111', 'Park.com', '2021-08-03 13:28:23'), (5, 'Yoo', 'Yoo@google.com', '010-4444-4444', 'Yoo.net', '2021-08-03 13:28:23')] 

OR๊ณผ ์ธ์ž์— dictionary์— key๋กœ ์—ฐ๊ฒฐ์‹œ์ผœ ์ฃผ์–ด ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜จ๋‹ค. 

 

 

 

(5) Dump ์ถœ๋ ฅ ( ์ค‘์š”! ) 

with conn:
    with open('./resource/dump.sql', 'w') as f:
        for line in conn.iterdump():
            f.write('%s\n' % line)
        print('Dump print Complete')

 Dump print Complete 

์ด๋ ‡๊ฒŒ ํ…Œ์ด๋ธ” ์ƒ์„ฑ, ๊ฐ’ ์‚ฝ์ž… ์—ฐ์‚ฐ๋“ค์„ ํ•œ ๋ฒˆ์— ๋ณผ ์ˆ˜ ์žˆ๋Š” ํŒŒ์ผ์ด ์ƒ์„ฑ ๋œ๋‹ค. 

 

 

 

(6) ์—ฐ๊ฒฐ ํ•ด์ œ

* f.close(), conn.close() : with๋ฌธ์„ ์‚ฌ์šฉํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ์ž๋™ ํ˜ธ์ถœ ๋œ๋‹ค. 

 

 

 

 

์ฝ”๋“œ - ํŒจ์บ  ์ˆ˜์—… ์ฝ”๋“œ ์ฐธ๊ณ  (ํŒจ์บ  ์ˆ˜์—… ์ •๋ฆฌ)

 

 

<์ด์ „ ๊ธ€>

https://silvercoding.tistory.com/44

 

[python ๊ธฐ์ดˆ] 12. ์™ธ๋ถ€ ํŒŒ์ผ ์ฒ˜๋ฆฌ (Excel, CSV ํŒŒ์ผ ์ฝ๊ธฐ ๋ฐ ์“ฐ๊ธฐ)

์ฝ”๋“œ - ํŒจ์บ  ์ˆ˜์—… ์ฝ”๋“œ ์ฐธ๊ณ  (ํŒจ์บ  ์ˆ˜์—… ์ •๋ฆฌ) <์ด์ „ ๊ธ€> https://silvercoding.tistory.com/43 https://silvercoding.tistory.com/42 https://silvercoding.tistory.com/41 https://silvercoding.tistory.com/40..

silvercoding.tistory.com

 

import sqlite3
import datetime

์šฐ์„  ์‚ฌ์šฉํ•  ๊ฒƒ import ํ•ด์ฃผ๊ธฐ 

 

 

- SQliteDatabaseBrowserPortable.exe ๋ฅผ ์„ค์น˜ํ•ด ์ค€๋‹ค. 

์ด๊ณณ์—์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ฅผ ์ง๊ด€์ ์œผ๋กœ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

 

- ์‚ฝ์ž… ๋‚ ์งœ ์ƒ์„ฑ 

now = datetime.datetime.now()
print('now: ', now)

nowDateTime = now.strftime('%Y-%m-%d %H:%M:%S')
print('nowDateTime: ', nowDateTime)

 now:  2021-08-03 11:43:31.850770 
 nowDateTime:  2021-08-03 11:43:31 

๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ๋„ฃ์–ด์ค„ ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์ „ ์ƒ์„ฑํ•œ๋‹ค.  

 

 

 

- sqlite3 ์‚ดํŽด๋ณด๊ธฐ 

print('sqlite3.version: ', sqlite3.version)
print('sqlite3.sqlite_version: ', sqlite3.sqlite_version)

 sqlite3.version:  2.6.0 
 sqlite3.sqlite_version:  3.33.0 

 

 

 

 

 

 

* sqlite ์‚ฌ์šฉ 

(1) DB ์ƒ์„ฑ & Auto Commit (Rollback) 

conn = sqlite3.connect('./resource/database.db', isolation_level=None)

DB๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ์—ฐ๊ฒฐํ•ด ์ค€๋‹ค. DB์— ๋ช…๋ นํ•  ๋•Œ ์ปค๋ฐ‹(commit)์„ ๊ผญ ํ•ด์ฃผ์–ด์•ผ ํ•˜๋Š”๋ฐ , isolation_level=None์œผ๋กœ ์„ค์ •ํ•˜๋ฉด AutoCommit์ด ๋œ๋‹ค. 

 

๊ทธ๋ฆฌ๊ณ  ์•„๊นŒ ๋‹ค์šด๋ฐ›์•˜๋˜ SQliteDatabaseBrowserPortable.exe ์—์„œ [ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์—ด๊ธฐ - database.db ] ๋ฅผ ์‹คํ–‰ ํ•ด ์ค€๋‹ค. 

 

 

(2) Cursor 

# Cursor 
c = conn.cursor()
print('Cursor Type: ', type(c))

 Cursor Type:  <class 'sqlite3.Cursor'> 

cursor ์—ฐ๊ฒฐ์„ ํ•ด์ค€๋‹ค. ์ด ์ปค์„œ๋กœ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ๋ช…๋ น์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

 

(3) ํ…Œ์ด๋ธ” ์ƒ์„ฑ CREATE TABLE 

( Data type : TEXT, NUMERIC, INTEGER, REAL BLOB )

c.execute('CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, username text, email text, phone text, website text, regdate text)')

 

ํ…Œ์ด๋ธ”์„ ์ƒ์„ฑํ•˜๊ธฐ ์œ„ํ•ด์„œ CREATE TABLE ๋ช…๋ น์–ด๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค. ๊ทธ๋‹ค์Œ ํ…Œ์ด๋ธ”์ด๋ฆ„(์†์„ฑ ํƒ€์ž…) ์ด๋Ÿฐ ํ˜•ํƒœ๋กœ ๋„ฃ์–ด์ค€๋‹ค. id ์†์„ฑ์„ PRIMARY KEY๋กœ ์„ค์ •ํ•ด ์ฃผ์—ˆ๋‹ค. 

์ด๋ ‡๊ฒŒ user ํ…Œ์ด๋ธ”์ด ์ƒ์„ฑ๋˜์—ˆ๋‹ค! 

 

 

(4) ๋ฐ์ดํ„ฐ ์‚ฝ์ž… INSERT INTO

# ๋ฐฉ๋ฒ• 1 
c.execute("INSERT INTO users VALUES(1, 'Kim', 'silver@naver.com', '010-0000-0000', 'kim.com', ?)", (nowDateTime,))
# ๋ฐฉ๋ฒ• 2 
c.execute('INSERT INTO users(id, username, email, phone, website, regdate) VALUES (?, ?, ?, ?, ?, ?)', (2, 'Park', 'Park@daum.net', '010-1111-1111', 'Park.com', nowDateTime))

- INSERT INTO ํ…Œ์ด๋ธ”์ด๋ฆ„ VALUES() 

- INSERT INTO ํ…Œ์ด๋ธ”์ด๋ฆ„() VALUES() 

๋ฐฉ๋ฒ• 1์€ ๋ฐ”๋กœ VALUES์•ˆ์— ๊ฐ’์„ ๋„ฃ๊ณ , ๋ณ€์ˆ˜๋ฅผ ๋„ฃ์„ ๊ฒฝ์šฐ ?๋กœ ์ž‘์„ฑํ•œ ํ›„ execute์˜ ์ธ์ž์—์„œ ํŠœํ”Œ์•ˆ์— ๋ณ€์ˆ˜๋ฅผ ๋„ฃ์–ด์ค€๋‹ค.  ๋ฐฉ๋ฒ• 2๋Š” ํ…Œ์ด๋ธ”์ด๋ฆ„() ์•ˆ์— ์†์„ฑ ์ด๋ฆ„์„ ๋ช…์‹œ์ ์œผ๋กœ ๋‚˜์—ดํ•˜๊ณ  , VALUES() ์•ˆ์— ๋ชจ๋‘ ? ๋กœ ์ž‘์„ฑํ•ด ์ฃผ๊ณ , execute์˜ ์ธ์ž์—์„œ ํŠœํ”Œ ์•ˆ์— ๊ฐ’ ๋˜๋Š” ๋ณ€์ˆ˜๋ฅผ ๋„ฃ์–ด์ค€๋‹ค. 

์ƒˆ๋กœ๊ณ ์นจ์„ ํ•ด์ฃผ๋ฉด ์œ„์™€ ๊ฐ™์ด ๊ฐ’์ด ์ƒ์„ฑ๋˜์—ˆ๋‹ค! 

 

 

(5) Many ์‚ฝ์ž… ( ํŠœํ”Œ, ๋ฆฌ์ŠคํŠธ ) 

userList = (
    (3, 'Lee', 'Lee@naver.com', '010-2222-2222', 'Lee.com', nowDateTime),
    (4, 'Cho', 'Cho@daum.net', '010-3333-3333', 'Cho.com', nowDateTime),
    (5, 'Yoo', 'Yoo@google.com', '010-4444-4444', 'Yoo.net', nowDateTime)
)

c.executemany('INSERT INTO users(id, username, email, phone, website, regdate) VALUES(?, ?, ?, ?, ?, ?)', userList)

excutemany์˜ ๋‘๋ฒˆ์งธ ์ธ์ž์— ํŠœํ”Œ์ด๋‚˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋„ฃ์–ด์ฃผ๋ฉด ํ•œ๊บผ๋ฒˆ์— ๋ฐ์ดํ„ฐ ์‚ฝ์ž…์ด ๊ฐ€๋Šฅํ•˜๋‹ค. 

 

 

(6) ํ…Œ์ด๋ธ” ๋ฐ์ดํ„ฐ ์‚ญ์ œ 

conn.execute('DELETE FROM users')

์ด๋ ‡๊ฒŒ ์ž‘์„ฑํ•ด ์ฃผ๋ฉด users ํ…Œ์ด๋ธ”์˜ ๋ชจ๋“  ๋ฐ์ดํ„ฐ๊ฐ€ ์‚ญ์ œ๋œ๋‹ค. 

 

 

- ์ง€์›Œ์ง„ ๊ฐœ์ˆ˜ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์‚ญ์ œํ•˜๊ธฐ 

print('users db delete : ', conn.execute('DELETE FROM users').rowcount)

 users db delete :  5 

rowcount๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ค„ ์ˆ˜ ์žˆ๋‹ค. 

 

 

(7) ์ปค๋ฐ‹ & ๋กค๋ฐฑ 

: isolation_level="None" ์ผ ๊ฒฝ์šฐ ์ž๋™ ๋ฐ˜์˜ 

# ์ปค๋ฐ‹
# conn.commit()

# ๋กค๋ฐฑ
# conn.rollback()

๋ณธ ํฌ์ŠคํŒ…์—์„  ์˜คํ† ์ปค๋ฐ‹ ์„ค์ •์„ ํ•ด๋†จ์œผ๋ฏ€๋กœ ์ฃผ์„์ฒ˜๋ฆฌ๋ฅผ ํ•ด ๋†“๋Š”๋‹ค. 

 

 

(8) ์ ‘์† ํ•ด์ œ 

conn.close()

๋งˆ๋ฌด๋ฆฌ ํ•  ๋•Œ๋Š” ์ ‘์†ํ•ด์ œ๋ฅผ ๊ผญ ํ•ด์ฃผ๋„๋ก ํ•œ๋‹ค! 

 

 

 

์ฝ”๋“œ - ํŒจ์บ  ์ˆ˜์—… ์ฝ”๋“œ ์ฐธ๊ณ  (ํŒจ์บ  ์ˆ˜์—… ์ •๋ฆฌ)

 

 

<์ด์ „ ๊ธ€>

https://silvercoding.tistory.com/43

 

[python ๊ธฐ์ดˆ] 11. ์˜ˆ์™ธ ์ข…๋ฅ˜์™€ ์ฒ˜๋ฆฌ , try , except , else, raise

์ฝ”๋“œ - ํŒจ์บ  ์ˆ˜์—… ์ฝ”๋“œ ์ฐธ๊ณ  (ํŒจ์บ  ์ˆ˜์—… ์ •๋ฆฌ) <์ด์ „ ๊ธ€> https://silvercoding.tistory.com/42 https://silvercoding.tistory.com/41 https://silvercoding.tistory.com/40 https://silvercoding.tistory.com/39..

silvercoding.tistory.com

 

 

 

import csv

์šฐ์„  ํŒŒ์ด์ฌ์—์„œ csv๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด import ํ•ด์ค€๋‹ค. 

 

 

 

 

- ์˜ˆ์ œ 1 

with open('./resource/sample1.csv', 'r') as f:
    reader = csv.reader(f)
    # next(reader) # Header ์Šคํ‚ต
    
    # ํ™•์ธ 
    print(reader)
    print(type(reader))
    print(dir(reader))
    print()

    for c in reader:
        print(c)  # ํ•˜๋‚˜์˜ row๊ฐ€ ๋ฆฌ์ŠคํŠธ ํ˜•์‹์œผ๋กœ ๋‚˜์˜จ๋‹ค.

<_csv.reader object at 0x0000013CD5F8E868>
<class '_csv.reader'>
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'dialect', 'line_num']

 

['๋ฒˆํ˜ธ', '์ด๋ฆ„', '๊ฐ€์ž…์ผ์‹œ', '๋‚˜์ด']
['1', '๊น€์ •์ˆ˜', '2017-01-19 11:30:00', '25']
['2', '๋ฐ•๋ฏผ๊ตฌ', '2017-02-07 10:22:00', '35']
['3', '์ •์ˆœ๋ฏธ', '2017-01-22 09:10:00', '33']
['4', '๊น€์ •ํ˜„', '2017-02-22 14:09:00', '45']
['5', 'ํ™๋ฏธ์ง„', '2017-04-01 18:00:00', '17']
['6', '๊น€์ˆœ์ฒ ', '2017-05-14 22:33:07', '22']
['7', '์ด๋™์ฒ ', '2017-03-01 23:44:45', '27']
['8', '๋ฐ•์ง€์ˆ™', '2017-01-11 06:04:18', '30']
['9', '๊น€์€๋ฏธ', '2017-02-08 07:44:33', '51']
['10', '์žฅํ˜์ฒ ', '2017-12-01 13:01:11', '16']

์—ฌ๊ธฐ์„œ header๋ฅผ ์ œ๊ฑฐํ•˜๊ณ  ์‹ถ์œผ๋ฉด ์œ„์˜ ์ฃผ์„์œผ๋กœ ์ž‘์„ฑ๋˜์–ด ์žˆ๋Š” next(reader)๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค. 

 

 

 

- ์˜ˆ์ œ 2 : delimiter 

vs๋กœ ์—ฌ๋‹ˆ๊นŒ ๊ธ€์”จ๊ฐ€ ๊นจ์ง€์ง€๋งŒ ์ฝค๋งˆ๊ฐ€ ์•„๋‹Œ |๋กœ ๊ตฌ๋ถ„๋˜์–ด ์žˆ๋Š” csvํŒŒ์ผ์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ตฌ๋ถ„์ž๋ฅผ , ์—์„œ | ๋กœ ๋ฐ”๊พธ์–ด์ฃผ์–ด์•ผ ํ•œ๋‹ค. 

with open('./resource/sample2.csv', 'r') as f:
    reader = csv.reader(f, delimiter='|')
    # next(reader) # Header ์Šคํ‚ต

    # ํ™•์ธ 
    print(reader)
    print(type(reader))
    print(dir(reader))
    print()

    for c in reader:
        print(c)

<_csv.reader object at 0x0000013CD5EA5798>
<class '_csv.reader'>
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'dialect', 'line_num']

['๋ฒˆํ˜ธ', '์ด๋ฆ„', '๊ฐ€์ž…์ผ์‹œ', '๋‚˜์ด']
['1', '๊น€์ •์ˆ˜', '2017-01-19 11:30:00', '25']
['2', '๋ฐ•๋ฏผ๊ตฌ', '2017-02-07 10:22:00', '35']
['3', '์ •์ˆœ๋ฏธ', '2017-01-22 09:10:00', '33']
['4', '๊น€์ •ํ˜„', '2017-02-22 14:09:00', '45']
['5', 'ํ™๋ฏธ์ง„', '2017-04-01 18:00:00', '17']
['6', '๊น€์ˆœ์ฒ ', '2017-05-14 22:33:07', '22']
['7', '์ด๋™์ฒ ', '2017-03-01 23:44:45', '27']
['8', '๋ฐ•์ง€์ˆ™', '2017-01-11 06:04:18', '30']
['9', '๊น€์€๋ฏธ', '2017-02-08 07:44:33', '51']
['10', '์žฅํ˜์ฒ ', '2017-12-01 13:01:11', '16']

delimiter = '|' ๋ฅผ ์‚ฌ์šฉํ–ˆ๋”๋‹ˆ ์ž˜ ๋‚˜๋ˆ„์–ด์ง„ ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค. 

 

 

 

- ์˜ˆ์ œ 3 : dictionary๋กœ ์ฝ์–ด์˜ค๊ธฐ => DictReader

with open('./resource/sample1.csv', 'r') as f:
    reader = csv.DictReader(f)

    for c in reader:
        for k, v in c.items():
            print(k, v)
        print("------------------")

๋ฒˆํ˜ธ 1
์ด๋ฆ„ ๊น€์ •์ˆ˜
๊ฐ€์ž…์ผ์‹œ 2017-01-19 11:30:00
๋‚˜์ด 25
------------------
๋ฒˆํ˜ธ 2
์ด๋ฆ„ ๋ฐ•๋ฏผ๊ตฌ
๊ฐ€์ž…์ผ์‹œ 2017-02-07 10:22:00
๋‚˜์ด 35
------------------
๋ฒˆํ˜ธ 3
์ด๋ฆ„ ์ •์ˆœ๋ฏธ
๊ฐ€์ž…์ผ์‹œ 2017-01-22 09:10:00
๋‚˜์ด 33
------------------
๋ฒˆํ˜ธ 4
์ด๋ฆ„ ๊น€์ •ํ˜„
๊ฐ€์ž…์ผ์‹œ 2017-02-22 14:09:00
๋‚˜์ด 45
------------------
๋ฒˆํ˜ธ 5
์ด๋ฆ„ ํ™๋ฏธ์ง„
๊ฐ€์ž…์ผ์‹œ 2017-04-01 18:00:00
๋‚˜์ด 17
------------------
๋ฒˆํ˜ธ 6
์ด๋ฆ„ ๊น€์ˆœ์ฒ 
๊ฐ€์ž…์ผ์‹œ 2017-05-14 22:33:07
๋‚˜์ด 22
------------------
๋ฒˆํ˜ธ 7
์ด๋ฆ„ ์ด๋™์ฒ 
๊ฐ€์ž…์ผ์‹œ 2017-03-01 23:44:45
๋‚˜์ด 27
------------------
๋ฒˆํ˜ธ 8
์ด๋ฆ„ ๋ฐ•์ง€์ˆ™
๊ฐ€์ž…์ผ์‹œ 2017-01-11 06:04:18
๋‚˜์ด 30
------------------
๋ฒˆํ˜ธ 9
์ด๋ฆ„ ๊น€์€๋ฏธ
๊ฐ€์ž…์ผ์‹œ 2017-02-08 07:44:33
๋‚˜์ด 51
------------------

DictReader๋ฅผ ํ†ตํ•˜์—ฌ ๋”•์…”๋„ˆ๋ฆฌ๋กœ ์ฝ์–ด์˜ค๋ฉด , 

OrderedDict([('๋ฒˆํ˜ธ', '1'), ('์ด๋ฆ„', '๊น€์ •์ˆ˜'), ('๊ฐ€์ž…์ผ์‹œ', '2017-01-19 11:30:00'), ('๋‚˜์ด', '25')])

์ด๋Ÿฐ ์‹์œผ๋กœ ํ•˜๋‚˜์˜ ์ค„๋งˆ๋‹ค OrderedDict๊ฐ€ ์ƒ์„ฑ๋œ๋‹ค. ๋”ฐ๋ผ์„œ ์œ„์™€ ๊ฐ™์€ ์ฝ”๋“œ๋กœ key์™€ value๋ฅผ ๋ฝ‘์•„๋‚ด์ค„ ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์ด๋‹ค. 

 

 

 

- ์˜ˆ์ œ 4 : writerow

w = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]

with open('./resource/sample3.csv', 'w', newline='') as f:
    wt = csv.writer(f)

    for v in w:
        wt.writerow(v)  # ํ•˜๋‚˜ํ•˜๋‚˜ ๊ฒ€์ˆ˜ํ•ด์„œ ์“ธ ๋–„ (if๊ฐ™์€ ์กฐ๊ฑด์ด ๋“ค์–ด๊ฐˆ ๋•Œ )

writerow๋กœ ํ•œ์ค„์”ฉ ๊ฒ€์ˆ˜ํ•ด๊ฐ€๋ฉฐ ์ž‘์„ฑ์„ ํ•ด์ค„ ์ˆ˜ ์žˆ๋‹ค.

 

 

 

- ์˜ˆ์ œ 5 : writerows 

with open('./resource/sample4.csv', 'w', newline='') as f:
    wt = csv.writer(f)
    wt.writerows(w)  # ์•„์— ํ•œ๋ฒˆ์— ์“ฐ๋Š” ๊ฒƒ

ํ•œ๋ฒˆ์— ์“ฐ๋Š” writerowsํ•จ์ˆ˜๋„ ์กด์žฌํ•œ๋‹ค. for๋ฌธ์„ ์‚ฌ์šฉํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค. 

 

 

 

- ์˜ˆ์ œ 6 : excel

* XSL, XLSX 

: openpyxl, xlswriter, xlrd, xlwt, xlutils 

: pandas ๋ฅผ ์ฃผ๋กœ ์‚ฌ์šฉ (openpyxl, xlrd) 

 

* ์„ค์น˜ (pandas, openpyxl, xlrd) 

- pip install xlrd

- pip install openpyxl

- pip install pandas 

 

 

* ๋ถˆ๋Ÿฌ์˜ค๊ธฐ 

import pandas as pd 

xlsx = pd.read_excel('./resource/sample.xlsx')

pandas๋ฅผ importํ•˜๊ณ , read_excel์„ ์ด์šฉํ•˜์—ฌ ์—‘์…€ ํŒŒ์ผ์„ ๋ถˆ๋Ÿฌ์™€ ์ค€๋‹ค. 

 

 

* ์ƒ์œ„ ๋ฐ์ดํ„ฐ ํ™•์ธ 

print(xlsx.head())

  Sap Co.      ๋Œ€๋ฆฌ์  ์˜์—…์‚ฌ์›       ์ „์›”       ๊ธˆ์›”  TEAM  ์ด ํŒ๋งค์ˆ˜๋Ÿ‰
0  KI1316  ๊ฒฝ๊ธฐ์ˆ˜์›๋Œ€๋ฆฌ์   ์ด๊ธฐ์ •  1720000  2952000     1     123
1  KI1451  ์ถฉ์ฒญํ™์„ฑ๋Œ€๋ฆฌ์   ์ •๋ฏธ์ง„  4080000  2706000     2     220
2  KI1534  ๊ฒฝ๊ธฐํ™”์„ฑ๋Œ€๋ฆฌ์   ๊ฒฝ์ธ์„    600000  2214000     1     320
3  KI1636  ๊ฐ•์›์†์ดˆ๋Œ€๋ฆฌ์   ์ด๋™๊ถŒ  3720000  2870000     3     110
4  KI1735  ๊ฒฝ๊ธฐ์•ˆ์–‘๋Œ€๋ฆฌ์   ๊ฐ•์ค€์„  4800000  2296000     1     134

๊ธฐ๋ณธ์ ์œผ๋กœ ๊ฐ€์žฅ ์œ„์˜ 5๊ฐœ ๋ฐ์ดํ„ฐ๊ฐ€ ๋‚˜์˜จ๋‹ค. 

 

 

* ํ•˜์œ„ ๋ฐ์ดํ„ฐ ํ™•์ธ 

print(xlsx.tail())

   Sap Co.       ๋Œ€๋ฆฌ์  ์˜์—…์‚ฌ์›       ์ „์›”       ๊ธˆ์›”  TEAM  ์ด ํŒ๋งค์ˆ˜๋Ÿ‰
15  KI2870  ๊ฒฝ๊ธฐ๊ตฌ๋ฆฌ์‹œ๋Œ€๋ฆฌ์   ๋ฐ•์ง„ํ˜•  6000000  3400000     2     143
16  KI2910   ๊ฐ•์›์ถ˜์ฒœ๋Œ€๋ฆฌ์   ๊น€์€ํ–ฅ  4800000  4896000     1     176
17  KI3030   ๊ฐ•์›์˜๋™๋Œ€๋ฆฌ์   ์ „์ˆ˜์ฐฝ  4560000  3128000     2      98
18  KI3131   ๊ฒฝ๊ธฐํ•˜๋‚จ๋Œ€๋ฆฌ์   ๊น€๋ฏผ์ •  2750000  7268000     3     293
19  KI3252   ๊ฐ•์›ํฌ์ฒœ๋Œ€๋ฆฌ์   ์„œ๊ฐ€์€  2420000  4740000     4     240

ํ•˜์œ„ 5๊ฐœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋ณด์—ฌ์ค€๋‹ค. 

 

 

* ๋ฐ์ดํ„ฐ์˜ ๊ตฌ์กฐ 

print(xlsx.shape) # ํ–‰, ์—ด

 (20, 7) 

shape๋ฅผ ์ด์šฉํ•˜์—ฌ ํ–‰๊ณผ ์—ด์˜ ํฌ๊ธฐ๊ฐ€ ์–ผ๋งˆ๋‚˜ ๋˜๋Š”์ง€ ํ™•์ธํ•ด ๋ณผ ์ˆ˜ ์žˆ๋‹ค. 

 

 

* ์—‘์…€ or CSV ๋‹ค์‹œ ์“ฐ๊ธฐ 

xlsx.to_excel('./resource/result.xlsx', index=False)
xlsx.to_csv('./resource/result.csv', index=False)

์ด๋ ‡๊ฒŒ to_excel๊ณผ to_csv๋ฅผ ์ด์šฉํ•˜์—ฌ ํŒŒ์ผ์„ ์ƒ์„ฑํ•  ์ˆ˜๋„ ์žˆ๋‹ค. 

 

 

 

์ฝ”๋“œ - ํŒจ์บ  ์ˆ˜์—… ์ฝ”๋“œ ์ฐธ๊ณ  (ํŒจ์บ  ์ˆ˜์—… ์ •๋ฆฌ)

 

 

<์ด์ „ ๊ธ€>

https://silvercoding.tistory.com/42

 

[python ๊ธฐ์ดˆ] 10. ํŒŒ์ผ ์ฝ๊ธฐ , ์“ฐ๊ธฐ (open)

์ฝ”๋“œ - ํŒจ์บ  ์ˆ˜์—… ์ฝ”๋“œ ์ฐธ๊ณ  (ํŒจ์บ  ์ˆ˜์—… ์ •๋ฆฌ) <์ด์ „ ๊ธ€> https://silvercoding.tistory.com/41 https://silvercoding.tistory.com/40 https://silvercoding.tistory.com/39 https://silvercoding.tistory.com/38..

silvercoding.tistory.com

 

 

* ๋ฌธ๋ฒ•์ ์œผ๋กœ ์—๋Ÿฌ๊ฐ€ ์—†์ง€๋งŒ, ์ฝ”๋“œ ์‹คํ–‰ (๋Ÿฐํƒ€์ž„) ํ”„๋กœ์„ธ์Šค์—์„œ ๋ฐœ์ƒํ•˜๋Š” ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๋„ ์ค‘์š”ํ•˜๋‹ค. 

* (cf) linter : ์ฝ”๋“œ ์Šคํƒ€์ผ, ๋ฌธ๋ฒ• ์ฒดํฌ 

 

 

์˜ค๋Š˜์€ ๋ฐ”๋ณด์ฝ”๋”ฉ์„ ํ•˜๋ฉด์„œ ์˜ค๋ฅ˜๊ฐ€ ์–ด๋–ป๊ฒŒ ๋ฐœ์ƒํ•˜๊ฒŒ ๋˜๋Š”์ง€ ์‚ดํŽด๋ณด์ž! 

 

 

 [ ์˜ˆ์™ธ ์ข…๋ฅ˜ ] 

(1) SyntaxError : ์ž˜๋ชป๋œ ๋ฌธ๋ฒ• 

print('Test)

 SyntaxError: EOL while scanning string literal 

if True
    pass

 SyntaxError: invalid syntax 

x => y

 SyntaxError: invalid syntax 

 

 

(2) NameError : ์ฐธ์กฐ๋ณ€์ˆ˜ ์—†์Œ 

a = 10 
b = 15 

print(c)

 NameError: name 'c' is not defined 

 

 

(3) ZeroDivisionError : 0 ๋‚˜๋ˆ„๊ธฐ ์—๋Ÿฌ 

print(10 / 0)

 ZeroDivisionError: division by zero 

 

 

(4) IndexError : ์ธ๋ฑ์Šค ๋ฒ”์œ„ ์˜ค๋ฒ„ 

x = [10, 20, 30]
print(x[0])
print(x[3]) # ์˜ˆ์™ธ ๋ฐœ์ƒ

 10 

 IndexError: list index out of range 

 

 

(5) KeyError : ์ฃผ๋กœ ๋”•์…”๋„ˆ๋ฆฌ์—์„œ ๋ฐœ์ƒ 

dic = {'name': 'Kim', 'Age': 33, 'city': 'Seoul'}
print(dic['hobby'])

 KeyError: 'hobby' 

print(dic.get('hobby'))  # ๊ถŒ์žฅ

 None 

์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š๊ณ  None์„ ๋ฐ˜ํ™˜ํ•˜๋Š” getํ•จ์ˆ˜ ์‚ฌ์šฉ์„ ๊ถŒ์žฅํ•œ๋‹ค. 

 

 

(6) AttributeError : ๋ชจ๋“ˆ , ํด๋ž˜์Šค์— ์žˆ๋Š” ์ž˜๋ชป๋œ ์†์„ฑ ์‚ฌ์šฉ ์‹œ 

import time
print(time.time())
print(time.month())

 1627887313.5666506 
Traceback (most recent call last):
  File "c:/Users/./Desktop/python_study/python_easy/section10.py", line 45, in <module>
    print(time.month())
 AttributeError: module 'time' has no attribute 'month' 

 

 

(7) ValueError

x = [1, 5, 9]
x.remove(10)

 ValueError: list.remove(x): x not in list 

x.index(10)

 ValueError: 10 is not in list 

 

 

(8) FileNotFoundError 

f = open('test.txt', 'r')  # ์˜ˆ์™ธ ๋ฐœ์ƒ

 FileNotFoundError: [Errno 2] No such file or directory: 'test.txt' 

 

 

(9) TypeError 

x = [1, 2]
y = (1, 2)
z = 'test'

print(x + y)

 TypeError: can only concatenate list (not "tuple") to list 

print(x + z)

 TypeError: can only concatenate list (not "str") to list 

print(x + list(y))

 [1, 2, 1, 2] 

๋ฆฌ์ŠคํŠธ๋Š” ๋ฆฌ์ŠคํŠธ๋ผ๋ฆฌ๋งŒ ํ•ฉ์น  ์ˆ˜ ์žˆ๋‹ค๋Š” ์—๋Ÿฌ๊ฐ€ ๋‚ฌ๊ณ , ์œ„์™€ ๊ฐ™์ด list๋กœ ํ˜•๋ณ€ํ™˜์„ ํ•ด์ฃผ๋ฉด ์—ฐ์‚ฐ์ด ๊ฐ€๋Šฅํ•ด์ง„๋‹ค. 

 

 

 

 

 

* ํ•ญ์ƒ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š์„ ๊ฒƒ์œผ๋กœ ๊ฐ€์ •ํ•˜๊ณ  ๋จผ์ € ์ฝ”๋”ฉ 

-> ๊ทธ ํ›„ ๋Ÿฐํƒ€์ž„ ์˜ˆ์™ธ ๋ฐœ์ƒ ์‹œ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ ์ฝ”๋”ฉ ๊ถŒ์žฅ ( EAFP ์ฝ”๋”ฉ ์Šคํƒ€์ผ ) 

 

 

 

 

 

[ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ ๊ธฐ๋ณธ ] 

* try : ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋Š” ์ฝ”๋“œ ์‹คํ–‰ (์—ฌ๊ธฐ์„œ ์—๋Ÿฌ๊ฐ€ ๋‚˜๋ฉด except๋กœ ๊ฐ„๋‹ค. ) 

* except : ์—๋Ÿฌ๋ช… 

* else : ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š์•˜์„ ๊ฒฝ์šฐ ์‹คํ–‰ 

* finally : ํ•ญ์ƒ ์‹คํ–‰ 

 

- ์˜ˆ์ œ 1 

name = ['Kim', 'Lee', 'Park']

try: 
    z = 'Kim'  # Cho : ์˜ˆ์™ธ ๋ฐœ์ƒ 
    x = name.index(z)
    print('{} Found it! in name'.format(z, x + 1))

except ValueError:
    print('Not found it! - Occured ValueError!')
else:
    print('OK! else!')

 Kim Found it! in name 

 OK! else! 

name = ['Kim', 'Lee', 'Park']

try: 
    z = 'Cho' 
    x = name.index(z)
    print('{} Found it! in name'.format(z, x + 1))

except ValueError:
    print('Not found it! - Occured ValueError!')
else:
    print('OK! else!')

 Not found it! - Occured ValueError! 

 

์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๊ธฐ ๋•Œ๋ฌธ์— except ๋ธ”๋Ÿญ์ด ์‹คํ–‰๋˜์—ˆ๋‹ค. 

 

 

- ์˜ˆ์ œ 2 

try: 
    z = 'jim' 
    x = name.index(z)
    print('{} Found it! in name'.format(z, x + 1))

except:
    print('Not found it! - Occured Error!')
else:
    print('OK! else!')

 Not found it! - Occured Error! 

 

 

- ์˜ˆ์ œ 3 

try: 
    z = 'Kim' 
    x = name.index(z)
    print('{} Found it! in name'.format(z, x + 1))

except:
    print('Not found it! - Occured Error!')
else:
    print('OK! else!')
finally:
    print("finally ok !")

 Kim Found it! in name 
 OK! else! 
 finally ok ! 

finally๋Š” ๋ฌด์กฐ๊ฑด ์‹คํ–‰๋œ๋‹ค. 

 

 

- ์˜ˆ์ œ 4 : ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋Š” ํ•˜์ง€ ์•Š์ง€๋งŒ , ๋ฌด์กฐ๊ฑด ์ˆ˜ํ–‰๋˜๋Š” ์ฝ”๋”ฉ ํŒจํ„ด 

try:
    print('try')
finally:
    print("ok finally!!!")

 try 
 ok finally!!! 

 

 

- ์˜ˆ์ œ 5 : ์—ฌ๋Ÿฌ ๊ฐœ์˜ except ๋ธ”๋Ÿญ 

try: 
    z = 'Kim' 
    x = name.index(z)
    print('{} Found it! in name'.format(z, x + 1))
# except Exception:  # ์ด๊ฑธ ์ฒ˜์Œ์— ๋†“์œผ๋ฉด ์•ˆ๋จ ! 
#     print('Not found it! - Occured Error!')
except ValueError:
    print('Not found it! - Occured ValueError!')
except IndexError:
    print('Not found it! - Occured IndexError!')
except Exception:
    print('Not found it! - Occured Error!')
else:
    print('OK! else!')
finally:
    print("finally ok !")

 Kim Found it! in name 
 OK! else! 
 finally ok ! 

์œ„์™€ ๊ฐ™์ด ์—๋Ÿฌ๋ฅผ ์—ฌ๋Ÿฌ ๊ฐœ ์žก์•„์ค„ ์ˆ˜๋„ ์žˆ๋‹ค. ์ด ๋•Œ Exception์„ ๊ฐ€์žฅ ์ฒซ ๋ฒˆ์งธ ๋„ฃ์–ด์ฃผ๋ฉด ๋ฐ‘์— ์ž์„ธํ•œ ์—๋Ÿฌ๋Š” ๋‚˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ์œ„์น˜ ์„ ์ •์„ ์ฃผ์˜ํ•˜์—ฌ์•ผ ํ•œ๋‹ค. ( Exception์ด ํฐ ๋ฒ”์œ„์ด๊ธฐ ๋•Œ๋ฌธ ) 

 

 

- ์˜ˆ์ œ 6 

* ์˜ˆ์™ธ ๋ฐœ์ƒ : raise ( raise ํ‚ค์›Œ๋“œ๋กœ ์˜ˆ์™ธ ์ง์ ‘ ๋ฐœ์ƒ ) 

try: 
    a = 'Jim'
    if a == 'Kim':
        print('OK ํ—ˆ๊ฐ€!')
    else:
        raise ValueError
except ValueError:
    print('๋ฌธ์ œ๋ฐœ์ƒ!')
except Exception as f: 
    print(f)
else:
    print('oK!')

 ๋ฌธ์ œ๋ฐœ์ƒ! 

raise๋ฅผ ์ด์šฉํ•˜์—ฌ ์ง์ ‘ ์˜ˆ์™ธ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ฌ ์ˆ˜๋„ ์žˆ๋‹ค. ์ด ์˜ˆ์ œ์—์„œ๋Š” ValueError๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๋ผ๊ณ  ํ•˜์˜€์œผ๋ฏ€๋กœ except ValueError๋ถ€๋ถ„์ด ์‹คํ–‰๋œ ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค. 

 

 

 

์ฝ”๋“œ - ํŒจ์บ  ์ˆ˜์—… ์ฝ”๋“œ ์ฐธ๊ณ  (ํŒจ์บ  ์ˆ˜์—… ์ •๋ฆฌ)

 

 

<์ด์ „ ๊ธ€>

https://silvercoding.tistory.com/41

 

[python ๊ธฐ์ดˆ] 9. ๋ชจ๋“ˆ๊ณผ ํŒจํ‚ค์ง€

์ฝ”๋“œ - ํŒจ์บ  ์ˆ˜์—… ์ฝ”๋“œ ์ฐธ๊ณ  (ํŒจ์บ  ์ˆ˜์—… ์ •๋ฆฌ) <์ด์ „ ๊ธ€> https://silvercoding.tistory.com/40 https://silvercoding.tistory.com/39 https://silvercoding.tistory.com/38 https://silvercoding.tistory.com/37..

silvercoding.tistory.com

 

 

<์ฐธ๊ณ > 

https://docs.python.org/3.7/library/functions.html#open

 

Built-in Functions — Python 3.7.11 documentation

Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order. abs(x) Return the absolute value of a number. The argument may be an integer or a floating po

docs.python.org

 

 

 

* ์ฝ๊ธฐ๋ชจ๋“œ : r / ์“ฐ๊ธฐ๋ชจ๋“œ (๊ธฐ์กด ํŒŒ์ผ ์‚ญ์ œ) : w / ์ถ”๊ฐ€๋ชจ๋“œ (ํŒŒ์ผ ์ƒ์„ฑ ๋˜๋Š” ์ถ”๊ฐ€ ) 

* ๋ณธ ํฌ์ŠคํŒ…์˜ txt ํŒŒ์ผ : ํŒจ์ŠคํŠธ ์บ ํผ์Šค ์ œ๊ณต (resource - *.txt) 

 

 

 

1. ํŒŒ์ผ ์ฝ๊ธฐ 

- ์˜ˆ์ œ 1 

f = open('./resource/review.txt', 'r')
content = f.read()
print(content)
print(dir(f))
# ๋ฐ˜๋“œ์‹œ close ๋ฆฌ์†Œ์Šค ๋ฐ˜ํ™˜ 
f.close()

The film, projected in the form of animation, 
imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues, 
which eventually paves the path for gaining a fresh perspective on an age-old problem. 
The story also happens to centre around two parallel characters, Shundi King and Hundi King, 
who are twins, but they constantly fight over unresolved issues planted in their minds 
by external forces from within their very own units. 

 ['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', 
'__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'reconfigure', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'write_through', 'writelines'] 

open์˜ ์ธ์ž์— 'r'์„ ์ž‘์„ฑํ•˜์—ฌ ์ฝ๊ธฐ๋ชจ๋“œ๋กœ txtํŒŒ์ผ์„ ๊ฐ€์ ธ ์˜จ๋‹ค. dir์„ ์ถœ๋ ฅํ•ด์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ฉ”์†Œ๋“œ๋“ค์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

 

- ์˜ˆ์ œ 2 : close ์ƒ๋žต ๊ฐ€๋Šฅ 

with open('./resource/review.txt', 'r') as f:
    c = f.read()
    print(c)
    print(list(c))
    print(iter(c))

The film, projected in the form of animation,
imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues,
which eventually paves the path for gaining a fresh perspective on an age-old problem.
The story also happens to centre around two parallel characters, Shundi King and Hundi King,
who are twins, but they constantly fight over unresolved issues planted in their minds
by external forces from within their very own units.
['T', 'h', 'e', ' ', 'f', 'i', 'l', 'm', ',', ' ', 'p', 'r', 'o', 'j', 'e', 'c', 't', 'e', 'd', ' ', 'i', 'n', ' ', 't', 'h', 'e', ' ', 'f', 'o', 'r', 'm', ' ', 'o', 'f', ' ', 'a', 'n', 'i', 'm', 'a', 't', 'i', 'o', 'n', ',', '\n', 'i', 'm', 'p', 'a', 
'r', 't', 's', ' ', 't', 'h', 'e', ' ', 'l', 'e', 's', 's', 'o', 'n', ' ', 'o', 'f', ' ', 'h', 'o', 'w', ' ', 'w', 'a', 'r', 's', ' ', 'c', 'a', 'n', ' ', 'b', 'e', ' ', 'e', 'l', 'u', 'd', 'e', 'd', ' ', 't', 'h', 'r', 'o', 'u', 'g', 'h', ' ', 'r', 'e', 'a', 's', 'o', 'n', 'i', 'n', 'g', ' ', 'a', 'n', 'd', ' ', 'p', 'e', 'a', 'c', 'e', 'f', 'u', 'l', ' ', 'd', 'i', 'a', 'l', 'o', 'g', 'u', 'e', 's', ',', '\n', 'w', 'h', 'i', 'c', 'h', ' ', 'e', 'v', 'e', 'n', 't', 'u', 'a', 'l', 'l', 'y', ' ', 'p', 'a', 'v', 'e', 's', ' ', 't', 'h', 'e', ' ', 'p', 'a', 't', 'h', ' ', 'f', 'o', 'r', ' ', 'g', 'a', 'i', 'n', 'i', 'n', 'g', ' ', 'a', ' ', 'f', 'r', 'e', 's', 'h', ' ', 'p', 'e', 'r', 's', 'p', 'e', 'c', 't', 'i', 'v', 'e', ' ', 'o', 'n', ' ', 'a', 
'n', ' ', 'a', 'g', 'e', '-', 'o', 'l', 'd', ' ', 'p', 'r', 'o', 'b', 'l', 'e', 'm', '.', '\n', 'T', 'h', 'e', ' ', 's', 't', 'o', 'r', 'y', ' ', 'a', 'l', 's', 'o', ' 
', 'h', 'a', 'p', 'p', 'e', 'n', 's', ' ', 't', 'o', ' ', 'c', 'e', 'n', 't', 'r', 'e', ' ', 'a', 'r', 'o', 'u', 'n', 'd', ' ', 't', 'w', 'o', ' ', 'p', 'a', 'r', 'a', 
'l', 'l', 'e', 'l', ' ', 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's', ',', ' ', 'S', 'h', 'u', 'n', 'd', 'i', ' ', 'K', 'i', 'n', 'g', ' ', 'a', 'n', 'd', ' ', 'H', 'u', 'n', 'd', 'i', ' ', 'K', 'i', 'n', 'g', ',', '\n', 'w', 'h', 'o', ' ', 'a', 'r', 'e', ' ', 't', 'w', 'i', 'n', 's', ',', ' ', 'b', 'u', 't', ' ', 't', 'h', 'e', 
'y', ' ', 'c', 'o', 'n', 's', 't', 'a', 'n', 't', 'l', 'y', ' ', 'f', 'i', 'g', 'h', 't', ' ', 'o', 'v', 'e', 'r', ' ', 'u', 'n', 'r', 'e', 's', 'o', 'l', 'v', 'e', 'd', ' ', 'i', 's', 's', 'u', 'e', 's', ' ', 'p', 'l', 'a', 'n', 't', 'e', 'd', ' ', 'i', 'n', ' ', 't', 'h', 'e', 'i', 'r', ' ', 'm', 'i', 'n', 'd', 's', '\n', 'b', 'y', 
' ', 'e', 'x', 't', 'e', 'r', 'n', 'a', 'l', ' ', 'f', 'o', 'r', 'c', 'e', 's', ' ', 'f', 'r', 'o', 'm', ' ', 'w', 'i', 't', 'h', 'i', 'n', ' ', 't', 'h', 'e', 'i', 'r', ' ', 'v', 'e', 'r', 'y', ' ', 'o', 'w', 'n', ' ', 'u', 'n', 'i', 't', 's', '.']   
 <str_iterator object at 0x00000230D67D2160> 

์œ„์™€ ๊ฐ™์ด with๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด close๋ฅผ ์ƒ๋žต ๊ฐ€๋Šฅํ•˜๋‹ค. with๋ฌธ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ๋ฉด close๋ฅผ ๊ผญ ์ž‘์„ฑํ•ด์ฃผ์–ด์•ผ ํ•˜๋Š” ๊ฒƒ์„ ์žŠ์ง€ ๋ง๊ธฐ. 

 

 

- ์˜ˆ์ œ 3 

with open('./resource/review.txt', 'r') as f:
    for c in f:
        print(c.strip())

 The film, projected in the form of animation, 
 imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues, 
 which eventually paves the path for gaining a fresh perspective on an age-old problem. 
 The story also happens to centre around two parallel characters, Shundi King and Hundi King, 
 who are twins, but they constantly fight over unresolved issues planted in their minds 
 by external forces from within their very own units. 

for๋ฌธ์œผ๋กœ ์ถœ๋ ฅํ•ด๋ณผ ์ˆ˜ ๋„ ์žˆ๋‹ค. stripํ•จ์ˆ˜๋กœ ๊ณต๋ฐฑ์„ ์ œ๊ฑฐํ•œ ๋’ค ์ถœ๋ ฅํ•ด ์ค€๋‹ค. 

 

 

- ์˜ˆ์ œ 4 

with open('./resource/review.txt', 'r') as f:
    content = f.read()
    print('>>>', content)
    content = f.read()  # ๋‚ด์šฉ ์—†์Œ 
    print('>>>', content)

 >>> The film, projected in the form of animation, 
 imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues, 
 which eventually paves the path for gaining a fresh perspective on an age-old problem. 
 The story also happens to centre around two parallel characters, Shundi King and Hundi King, 
 who are twins, but they constantly fight over unresolved issues planted in their minds 
 by external forces from within their very own units. 
 >>> 

์ด๋ ‡๊ฒŒ ๋ชจ๋“  line์„ ์ถœ๋ ฅํ•˜๊ณ  ๋‚˜๋ฉด, ์ค‘๋ณตํ•ด์„œ line์„ ๋ถˆ๋Ÿฌ์˜ฌ ์ˆ˜ ์—†๋‹ค. ์ด๋ฏธ ์ปค์„œ๊ฐ€ ๋๊นŒ์ง€ ๊ฐ”๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. 

 

 

- ์˜ˆ์ œ 5 : readline() 

with open('./resource/review.txt', 'r') as f:
    line = f.readline()
    # print(line)
    while line:
        print(line, end='####')
        line = f.readline()

The film, projected in the form of animation,
####imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues,
####which eventually paves the path for gaining a fresh perspective on an age-old problem.
####The story also happens to centre around two parallel characters, Shundi King and Hundi King,
####who are twins, but they constantly fight over unresolved issues planted in their minds
####by external forces from within their very own units.####

readline()์€ ํ•œ์ค„์”ฉ ๋ฐ˜ํ™˜ ํ•ด ์ค€๋‹ค. 

 

 

- ์˜ˆ์ œ 6 : readlines() 

with open('./resource/review.txt', 'r') as f:
    contents = f.readlines()
    print(contents)
    for c in contents:
        print(c, end=" ****** ")

['The film, projected in the form of animation,\n', 'imparts the lesson of how wars 
can be eluded through reasoning and peaceful dialogues,\n', 'which eventually paves 
the path for gaining a fresh perspective on an age-old problem.\n', 'The story also 
happens to centre around two parallel characters, Shundi King and Hundi King,\n', 'who are twins, but they constantly fight over unresolved issues planted in their minds\n', 'by external forces from within their very own units.']
The film, projected in the form of animation,
 ****** imparts the lesson of how wars can be eluded through reasoning and peaceful 
dialogues,
 ****** which eventually paves the path for gaining a fresh perspective on an age-old problem.
 ****** The story also happens to centre around two parallel characters, Shundi King and Hundi King,
 ****** who are twins, but they constantly fight over unresolved issues planted in their minds
 ****** by external forces from within their very own units. ******

readlines๋Š” ๋ชจ๋“  ๋ฌธ์žฅ์„ ๋ฆฌ์ŠคํŠธ์— ๋„ฃ์–ด์ค€๋‹ค. 

 

 

- ์˜ˆ์ œ 7 

score = []

with open('./resource/score.txt', 'r') as f:
    for line in f:
        score.append(int(line))
    print(score)
    
print('Average : {:6.3}'.format(sum(score)/len(score)))

 [95, 78, 92, 89, 100, 66] 
 Average :   86.7 

ํ˜•๋ณ€ํ™˜์„ ํ•˜๊ณ , ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€ํ•ด์„œ ํ‰๊ท ์„ ๊ตฌํ•ด์ฃผ๋Š” ์˜ˆ์ œ์ด๋‹ค. 

 

 

 

 

 

 

 

 

 

2. ํŒŒ์ผ ์“ฐ๊ธฐ 

- ์˜ˆ์ œ 1 

with open('./resource/text1.txt', 'w') as f:
    f.write("Nicegirl!\n")

open์˜ ์ธ์ž์— 'w'๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํŒŒ์ผ์„ ์ƒ์„ฑ ๋ฐ ๊ธ€์„ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

 

- ์˜ˆ์ œ 2 

with open('./resource/text1.txt', 'a') as f:
    f.write("Goodgirl!")

open์˜ ์ธ์ž์— 'a'๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ธ€์”จ๋ฅผ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

 

- ์˜ˆ์ œ 3 

from random import randint
with open('./resource/text2.txt', 'w') as f:
    for cnt in range(6):
        f.write(str(randint(1, 50)))
        f.write('\n')

for๋ฌธ์„ ์ด์šฉํ•˜์—ฌ 6๊ฐœ์˜ ๋žœ๋ค ์ˆซ์ž๋ฅผ ๊ฐ ์ค„์— ํ•œ๊ฐœ์”ฉ ์ž‘์„ฑํ•ด ์ฃผ๋Š” ์ฝ”๋“œ์ด๋‹ค. 

 

 

- ์˜ˆ์ œ 4 >>> writelines : ๋ฆฌ์ŠคํŠธ -> txt ํŒŒ์ผ๋กœ ์ €์žฅ 

# writelines : ๋ฆฌ์ŠคํŠธ -> ํŒŒ์ผ๋กœ ์ €์žฅ
with open('./resource/text3.txt', 'w') as f:
    list = ['Kim\n', 'Park\n', 'Cho\n']
    f.writelines(list)

writelines๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฆฌ์ŠคํŠธ๋ฅผ ํŒŒ์ผ๋กœ ์ €์žฅํ•ด์ค„ ์ˆ˜๋„ ์žˆ๋‹ค. 

 

 

- ์˜ˆ์ œ 5 : ํ”„๋ฆฐํŠธ ํ•จ์ˆ˜๋กœ ํŒŒ์ผ ์ƒ์„ฑ 

with open('./resource/text4.txt', 'w') as f:
    print('Test Contents1!', file=f)
    print('Test Contents2!', file=f)

printํ•จ์ˆ˜์˜ ์ธ์ž์— file=f ๋ฅผ ๋„ฃ์–ด์ฃผ๋ฉด ํŒŒ์ผ๋กœ ์ƒ์„ฑ์ด ๊ฐ€๋Šฅํ•˜๋‹ค. 

 

 

 

์ฝ”๋“œ - ํŒจ์บ  ์ˆ˜์—… ์ฝ”๋“œ ์ฐธ๊ณ  (ํŒจ์บ  ์ˆ˜์—… ์ •๋ฆฌ)

 

 

<์ด์ „ ๊ธ€>

https://silvercoding.tistory.com/40

 

[python ๊ธฐ์ดˆ] 8. ํด๋ž˜์Šค , ์ƒ์† , ๋‹ค์ค‘์ƒ์†

์ฝ”๋“œ - ํŒจ์บ  ์ˆ˜์—… ์ฝ”๋“œ ์ฐธ๊ณ  (ํŒจ์บ  ์ˆ˜์—… ์ •๋ฆฌ) <์ด์ „ ๊ธ€> https://silvercoding.tistory.com/39 https://silvercoding.tistory.com/38 https://silvercoding.tistory.com/37 https://silvercoding.tistory.com/36..

silvercoding.tistory.com

 

* ํด๋” - ํŒจํ‚ค์ง€, ํŒŒ์ผ - ๋ชจ๋“ˆ ์ด๋ผ๊ณ  ํ•  ์ˆ˜ ์žˆ๋‹ค. 

* ์ƒ๋Œ€ ๊ฒฝ๋กœ - . : ๋ถ€๋ชจ ๋””๋ ‰ํ† ๋ฆฌ / .. : ํ˜„์žฌ ๋””๋ ‰ํ† ๋ฆฌ 

 

 

 

์šฐ์„  ์˜ค๋Š˜ ์‹ค์Šต์„ ์œ„ํ•ด์„œ 

pkg ํด๋”๋ฅผ ์ƒ์„ฑํ•˜๊ณ , ๊ทธ ์•ˆ์— ํŒŒ์ผ์„ ๋งŒ๋“ค์–ด ์ค€๋‹ค. 

 

(1) __init__.py 

* ์šฉ๋„ : ํ•ด๋‹น ๋””๋ ‰ํ† ๋ฆฌ๊ฐ€ ํŒจํ‚ค์ง€์ž„์„ ์„ ์–ธ 

* Python 3.x : ํŒŒ์ผ์ด ์—†์–ด๋„ ํŒจํ‚ค์ง€๋ฅผ ์ธ์‹ ํ•˜์ง€๋งŒ , ํ•˜์œ„ ํ˜ธํ™˜์„ ์œ„ํ•ด ์ƒ์„ฑํ•ด ๋†“๋Š” ๊ฒƒ์„ ์ถ”์ฒœํ•œ๋‹ค. 

 

 

(2) fibonacci.py 

class Fibonacci:
    def __init__(self, title='fibonacci'):
        self.title = title 

    def fib(n):  # ํ”ผ๋ณด๋‚˜์น˜ ์ถœ๋ ฅ
        a, b = 0, 1 
        while a < n:
            print(a, end=' ')
            a, b = b, a + b 
        print()

    def fib2(n): # ํ”ผ๋ณด๋‚˜์น˜ ๋ฆฌ์ŠคํŠธ ๋ฆฌํ„ด 
        result = []
        a, b = 0, 1 
        while a < n:
            result.append(a)
            a, b = b, a + b 

        return result

fib๋Š” ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด์„ ์ถœ๋ ฅ, fib2๋Š” ๋ฆฌ์ŠคํŠธ๋กœ ์ถœ๋ ฅํ•ด ์ฃผ๋Š” ํ•จ์ˆ˜์ด๋‹ค. 

 

 

(3) calculations.py

def add(l, r):
    return l + r

def mul(l, r):
    return l * r

def div(l, r):
    return l / r

๋”ํ•˜๊ธฐ, ๊ณฑํ•˜๊ธฐ, ๋‚˜๋ˆ„๊ธฐ ๋‹จ์ˆœ ๊ณ„์‚ฐ ํ•จ์ˆ˜๋‹ค. 

 

 

(4) prints.py

def prt1():
    print("I'm NiceGirl!")


def prt2():
    print("I'm GoodGirl!")


# ๋‹จ์œ„ ์‹คํ–‰ (๋…๋ฆฝ์ ์œผ๋กœ ํŒŒ์ผ ์‹คํ–‰) : ํ•จ์ˆ˜๊ฐ€ ์ž˜ ๋งŒ๋“ค์–ด ์กŒ๋Š”์ง€ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด ์ด ํŒŒ์ผ์—์„œ๋งŒ ์‹คํ–‰ํ•˜๋„๋ก ์„ค์ • 
if __name__ == "main":
    prt1()
    prt2()

๋‹จ์ˆœ ์ถœ๋ ฅ๋ฌธ์ด๊ณ , ๋‹จ์œ„์‹คํ–‰์œผ๋กœ ๋‹ค๋ฅธ ํŒŒ์ผ์—์„œ ์ด ๋ชจ๋“ˆ์„ ์‹คํ–‰ํ–ˆ์„ ๋•Œ ์ถœ๋ ฅ๋˜์ง€ ์•Š๊ณ , ํ˜„์žฌ ํŒŒ์ผ์—์„œ๋งŒ ์‹คํ–‰์ด ๋˜๋„๋ก ํ•˜๋Š” if๋ฌธ์€ ์„ ์–ธํ•œ๋‹ค. 

 

 

 

 

- ์˜ˆ์ œ 1 : ํด๋ž˜์Šค 

from pkg.fibonacci import Fibonacci

์œ„์™€ ๊ฐ™์ด ํด๋ž˜์Šค๋ฅผ importํ•ด ์˜ฌ ์ˆ˜ ์žˆ๋‹ค. 

Fibonacci.fib(300)

 0 1 1 2 3 5 8 13 21 34 55 89 144 233 

์ธ์Šคํ„ด์Šค ๋ฉ”์†Œ๋“œ๊ฐ€ ์•„๋‹Œ ํด๋ž˜์Šค ๋ฉ”์†Œ๋“œ์˜€์œผ๋ฏ€๋กœ ํด๋ž˜์Šค ์ž์ฒด๋กœ ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๋‹ค. 

print("ex1 : ", Fibonacci.fib2(400))
print('ex1 : ', Fibonacci().title)  # ์ธ์Šคํ„ด์Šคํ™” ์‹œ์ผœ์•ผ ํ•จ.

 ex1 :  [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377] 
 ex1 :  fibonacci 

title์€ ์ธ์Šคํ„ด์Šค ๋ณ€์ˆ˜๊ธฐ ๋•Œ๋ฌธ์— ์ธ์Šคํ„ด์Šคํ™” ์‹œ์ผœ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค. 

 

 

- ์˜ˆ์ œ 2 : ํด๋ž˜์Šค 2 

from pkg.fibonacci import *

๋ชจ๋“ˆ์˜ ๋ชจ๋“  ํด๋ž˜์Šค๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค. ์ด ๋ฐฉ๋ฒ•์€ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ๋งŽ์ด ์ฐจ์ง€ํ•˜๋ฏ€๋กœ ๊ถŒ์žฅ๋˜์ง€ ์•Š๋Š”๋‹ค. ํ•„์š”ํ•œ ๊ฒƒ๋งŒ ๋ถˆ๋Ÿฌ์˜ค๋Š” ๊ฒƒ์ด ํšจ์œจ์ ์ด๋‹ค. 

Fibonacci.fib(500)
print("ex2 : ", Fibonacci.fib2(600))
print('ex2 : ', Fibonacci().title)  # ์ธ์Šคํ„ด์Šคํ™” ์‹œ์ผœ์•ผ ํ•จ.

 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 
 ex2 :  [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377] 
 ex2 :  fibonacci 

 

 

- ์˜ˆ์ œ 3 : ํด๋ž˜์Šค - ๊ถŒ์žฅํ•˜๋Š” ๋ฐฉ๋ฒ• 

from pkg.fibonacci import Fibonacci as fb

์ด์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ๋งŽ์ด ๋ณด์•˜์„ ๊ฒƒ์ด๋‹ค. 

fb.fib(1000)
print("ex3 : ", fb.fib2(1600))
print('ex3 : ', fb().title)

 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 
 ex3 :  [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]     
 ex3 :  fibonacci 

 

 

- ์˜ˆ์ œ 4 : ํ•จ์ˆ˜ 

import pkg.calculations as c
print("ex4 : ", c.add(10, 100))
print("ex4 : ", c.mul(10, 100))

 ex4 :  110 
 ex4 :  1000 

 

 

 

- ์˜ˆ์ œ 5 : ํ•จ์ˆ˜ - ๊ถŒ์žฅํ•˜๋Š” ๋ฐฉ๋ฒ• (ํ•„์š”ํ•œ ๋งŒํผ๋งŒ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹์€ ์Šต๊ด€์ด๋‹ค. ) 

from pkg.calculations import div as d
print('ex5 : ', int(d(100, 10)))

 ex5 :  10 

์ด๋ ‡๊ฒŒ ํ•„์š”ํ•œ ํ•จ์ˆ˜๋งŒ ๋ถˆ๋Ÿฌ์™€์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

 

- ์˜ˆ์ œ 6 

import pkg.prints as p
import builtins  # ํŒŒ์ด์ฌ์—์„œ ๊ธฐ๋ณธ์ ์œผ๋กœ ์ œ๊ณตํ•˜๋Š” ํ•จ์ˆ˜๋“ค
p.prt1()
p.prt2()
print()
print(dir(builtins))

 I'm NiceGirl! 
 I'm GoodGirl! 

 ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'] 

builtins์—๋Š” ํŒŒ์ด์ฌ์—์„œ ๊ธฐ๋ณธ์ ์œผ๋กœ ์ œ๊ณตํ•˜๋Š” ํ•จ์ˆ˜๋“ค์ธ๋ฐ, prints.py์—์„œ ์‚ฌ์šฉํ–ˆ๋˜ __name__์ด ๋“ค์–ด๊ฐ€ ์žˆ๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค. 

 

 

 

+ Recent posts