๐Ÿ“‚์›น ๊ฐœ๋ฐœ(Web)/๐ŸํŒŒ์ด์ฌ(Python)

ํŒŒ์ผ๋ณต์‚ฌ/csvํŒŒ์ผ ์ฝ๊ธฐ ์“ฐ๊ธฐ

๐Ÿ‘ฉ‍๐ŸŽ“์ธํ…”๋ฆฌ๊ฐ์ž๐Ÿฅ” 2023. 2. 8. 17:18

1. ํŒŒ์ผ๋ณต์‚ฌ

ํŒŒ์ผ๋ณต์‚ฌ
    ์›๋ณธ -> ๋ฒ„ํผ ๋ณ€์ˆ˜(Memory) -> ๋ณต์‚ฌ๋ณธ
buffer_size = 1024 #1024 byte -> 1 KB ์˜๋ฏธ
with open('../../Day07/Section13/hello.txt', 'rb') as source:
    with open('hello2.txt', 'wb') as copy:
        while True:
            buffer = source.read(buffer_size)
            if not buffer:
                break
            copy.write(buffer)
print('hello2.txt ํŒŒ์ผ์ด ๋ณต์‚ฌ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค')

 

2. CSV ํŒŒ์ผ

CSV(comma-seperated values)
    ํ•„๋“œ๋ฅผ ์‰ผํ‘œ(,)๋กœ ๊ตฌ๋ถ„ํ•œ
    ํ…์ŠคํŠธ ๋ฐ์ดํ„ฐ ํŒŒ์ผ์ด๋‹ค.

์˜ˆ์ œ1) csvReader

student_list = []
with open('ํ•™์ƒ๋ช…๋‹จ.csv', 'rt', encoding='UTF-8') as file:
    file.readline()
    while True:
        line = file.readline()
        if not line:
            break
        student = line.split(',')
        student_list.append(student)
print(student_list)

์˜ˆ์ œ2) csvWriter

#์ฒซ ๋ฒˆ์งธ ๋ฐฉ๋ฒ•
import csv

with open('์ฐจ๋Ÿ‰๊ด€๋ฆฌ.csv', 'w', encoding='UTF-8') as file:
    csv_maker = csv.writer(file, delimiter=',')
    csv_maker.writerow([1, '08๋Ÿฌ1234', '2020-10-20,14:00'])
    csv_maker.writerow([2, '25๋‹ค1234', '2020-10-20,14:10'])
    csv_maker.writerow([3, '28ํ•˜1234', '2020-10-20,14:20'])
print('์ฐจ๋Ÿ‰๊ด€๋ฆฌ.csv ํŒŒ์ผ์ด ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.')

# ๋‘ ๋ฒˆ์งธ ๋ฐฉ๋ฒ•
import csv

with open('์ฐจ๋Ÿ‰๊ด€๋ฆฌ.csv', 'w', newline='', encoding='UTF-8') as file:
    csv_maker = csv.writer(file, delimiter=',') # ์ฝค๋งˆ๋กœ ๊ตฌ๋ถ„ํ•˜๊ฒ ๋‹ค.
    csv_maker.writerow([1, '08๋Ÿฌ1234', '2020-10-20,14:00'])
    csv_maker.writerow([2, '25๋‹ค1234', '2020-10-20,14:10'])
    csv_maker.writerow([3, '28ํ•˜1234', '2020-10-20,14:20'])
print('์ฐจ๋Ÿ‰๊ด€๋ฆฌ.csv ํŒŒ์ผ์ด ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.')
# ๋งˆ์ง€๋ง‰ ๋ฐฉ๋ฒ•
import csv

with open('์ฐจ๋Ÿ‰๊ด€๋ฆฌ.csv', 'w', newline='', encoding='UTF-8') as file:
    csv_maker = csv.writer(file, delimiter=',', quotechar='"')
    csv_maker.writerow([1, '08๋Ÿฌ1234', '2020-10-20,14:00'])
    csv_maker.writerow([2, '25๋‹ค1234', '2020-10-20,14:10'])
    csv_maker.writerow([3, '28ํ•˜1234', '2020-10-20,14:20'])
print('์ฐจ๋Ÿ‰๊ด€๋ฆฌ.csv ํŒŒ์ผ์ด ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.')

 

์˜ˆ์ œ3) csvQuoteReader

member_list = []
with open('ํšŒ์›๋ช…๋‹จ.csv', 'rt', encoding='UTF-8') as file:
    file.readline() # ์ฒซ ์ค„ ์ œ๊ฑฐ
    while True:
        line = file.readline()
        if not line:
            break
        member = line.split(',')
        member[0] = member[0].strip('"') # ์–‘์ชฝ ์ œ๊ฑฐ
        member[2] = member[2].strip('\n')

        member_list.append(member)

print(member_list)

์˜ˆ์ œ4) csvReader

import csv

with open('์ฐจ๋Ÿ‰๊ด€๋ฆฌ.csv', 'r', newline='', encoding='UTF-8') as file:
    csv_reader = csv.reader(file, delimiter=',', quotechar='"')
    for line in csv_reader:
        print(line)