๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
IT-Engineering/Python

Python ๋ฆฌ์ŠคํŠธ(list) csv ํŒŒ์ผ๋กœ ์ฝ๊ณ  ์“ฐ๊ธฐ(๋ถˆ๋Ÿฌ์˜ค๊ธฐ, ์ €์žฅํ•˜๊ธฐ)

by ๐Ÿงž‍โ™‚๏ธ 2020. 8. 7.
๋ฐ˜์‘ํ˜•

๋”ฅ๋Ÿฌ๋‹ ๋“ฑ AI๊ด€๋ จ ์ž‘์—…์„ ํ•˜๋‹ค๋ณด๋ฉด csv๋ฅผ ๊ฐ€์ ธ์™€์„œ ์—ด๊ณ  ์ž‘์—…์„ ํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์ œ๋ฒ• ๋งŽ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ, ๋ง‰์ƒ ์ง์ ‘ ๋งŒ๋“  ์ฝ”๋“œ์—์„œcsv๋ฅผ ๋ฝ‘์•„๋‚ด๊ณ  ๊ทธ ํŒŒ์ผ์„ ๋ถˆ๋Ÿฌ๋“ค์ด๋ ค๋‹ค ๋ณด๋ฉด ์ฝ”๋“œ ์ž‘์„ฑ์ด ํ—ท๊ฐˆ๋ฆด ๋•Œ๊ฐ€ ์žˆ๋”ฐ.

๊ทธ๋ž˜์„œ ํŠน์ • ์˜ˆ์ œ๋ฅผ ๋งŒ๋“ค์–ด csvํŒŒ์ผ์„ ์ฝ๋Š” ๊ณผ์ •๊ณผ ์“ฐ๋Š” ๊ณผ์ •์„ ๊ฐ๊ฐ ๋ณด์ด๋„๋ก ํ•˜๊ฒ ๋‹ค.

Python ๋ฆฌ์ŠคํŠธ csv๋กœ ์ €์žฅํ•˜๊ธฐ

ํŒŒ์ด์ฌ ๋ชจ๋“ˆ์ธ csv ๋ชจ๋“ˆ์„ importํ•˜๊ณ  ๋ฐ์ดํ„ฐ๋Š” ๋‚ ์งœ ๋ฐ์ดํ„ฐ, ์ •์ˆ˜ ๋ฐ์ดํ„ฐ, ๋ถ€๋™์†Œ์ˆ˜์  ์ž๋ฃŒํ˜• ๋ฐ์ดํ„ฐ๊ฐ€ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ–ˆ๋‹ค. ์—‘์…€๋กœ ๊ทธ๋ฆฐ๋‹ค๋ฉด ์—ด ๋ฐฉํ–ฅ์œผ๋กœ ๊ทธ๋ฆด ๊ฒƒ ๊ฐ™์ง€๋งŒ, ํŒŒ์ด์ฌ ๋ฆฌ์ŠคํŠธ๋กœ ํ‘œํ˜„ํ•˜์—ฌ ํ–‰ ๋ฐฉํ–ฅ์œผ๋กœ ๋‚˜์—ด๋˜์—ˆ๋‹ค.

# csv ๋ชจ๋“ˆ importํ•˜๊ธฐ
import csv

# list ๋งŒ๋“ค๊ธฐ
date = ['200801','200802','200803','200804','200805']
val1 = [50,100,300,150,200]
val2 = [2000.0, 2200.5, 2320.3, 2250.0, 2200.0]

# csvํŒŒ์ผ๋กœ ์ ๊ธฐ
# newline ์„ค์ •์„ ์•ˆํ•˜๋ฉด ํ•œ์ค„๋งˆ๋‹ค ๊ณต๋ฐฑ์žˆ๋Š” ์ค„์ด ์ƒ๊ธด๋‹ค.
with open('listfile.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(date)
    writer.writerow(val1)
    writer.writerow(val2)

csvํŒŒ์ผ ์ถœ๋ ฅ๊ฒฐ๊ณผ:

>>
200801,200802,200803,200804,200805
50,100,300,150,200
2000.0,2200.5,2320.3,2250.0,2200.0

Python์—์„œ ์ €์žฅํ–ˆ๋˜ csvํŒŒ์ผ ๋ฆฌ์ŠคํŠธ๋กœ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ

์•ž์„œ ํ–‰๋ฐฉํ–ฅ์œผ๋กœ ๋‚˜์—ดํ–ˆ๋˜ ๊ฐ ์ค„(line)์„ csv ๋ชจ๋“ˆ์„ ์ด์šฉํ•˜๋ฉด ๋ฐ”๋กœ ๋ฆฌ์ŠคํŠธ๋กœ ๋ถˆ๋Ÿฌ๋“ค์ด๋Š” ๊ฒƒ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

# csv ํŒŒ์ผ ์ฝ๊ธฐ
with open('listfile.csv', 'r', encoding='utf-8') as f:
    rdr = csv.reader(f)
    for i,line in enumerate(rdr):
        if i==0:
            date = line
        elif i==1:
            val1 = line
        elif i==2:
            val2 = line

์ด ๊ฒฝ์šฐ์—๋Š” ๊ฐ ๋ผ์ธ์ด ์–ด๋–ค ๋ฐ์ดํ„ฐ๋ฅผ ์•„๋Š” ๊ฒฝ์šฐ์ด๊ธฐ ๋•Œ๋ฌธ์— ์ค„๋งˆ๋‹ค ํŠน์ • ๋ฆฌ์ŠคํŠธ ์ž๋ฃŒํ˜•์„ ๋งŒ๋“ค์–ด ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฐ›์•„์™”๋‹ค. ์ผ๋ฐ˜์ ์œผ๋กœ ํŒŒ์ผ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ์—์„œ๋Š” readlineํ•ด์„œ ๋ถˆ๋Ÿฌ์˜จ ๋ผ์ธ์ด str์ž๋ฃŒํ˜•์ธ๋ฐ, ์ด ๊ฒฝ์šฐ์—๋Š” ๋ฐ”๋กœ list ์ž๋ฃŒํ˜•์œผ๋กœ ๋“ค์–ด์˜ค๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด ์•„๋ž˜์™€ ๊ฐ™์ด ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด์„œ ๊ฒฐ๊ณผ๋ฅผ ๋ณด์ž.

print(date)
print(val1)
print(val2)

์ถœ๋ ฅ๊ฒฐ๊ณผ:

>>
['200801', '200802', '200803', '200804', '200805']
['50', '100', '300', '150', '200']
'2000.0', '2200.5', '2320.3', '2250.0', '2200.0']

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€