1. ํ์ผ ์ฝ๊ธฐ
open() ํจ์๋ฅผ ์ด์ฉํด ํ์ผ์ ๋ถ๋ฌ์ ๋ณ์์ ์ ์ฅํ๋ค.
read() ๋ฉ์๋๋ฅผ ์ด์ฉํด ํ์ผ์ ์ฝ์ ์ ์๋ ํํ๋ก ๋ณํํ๋ค.
close() ๋ฉ์๋๋ฅผ ์ด์ฉํด ์ฌ์ฉํ์ง ์๋ ํ์ผ์ ๋ซ์ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ ์ฝํ๋ค.
# ํ์ผ ์ด๊ธฐ/๋ซ๊ธฐ
file = open('data.txt')
content = file.read()
file.close()
with open() as file: ๊ตฌ๋ฌธ์ ํ์ฉํด indent ๋ฒ์๊ฐ ๋๋๋ฉด ํ์ผ์ด ์๋์ ์ผ๋ก ๋ซํ๊ฒ ํ๋ค.
# ํ์ผ ์๋์ผ๋ก ๋ซ๊ธฐ
with open('data.txt') as file:
content =file.read()
์ค ๋จ์๋ก ์ฝ๊ธฐ
with open('data.txt') as file:
for line in file:
print(line)
๋๋ฒ์งธ ์ธ์์ 'w' ์ต์ ์ ์ฃผ์ด, ์ฐ๊ธฐ ๋ชจ๋๋ก ํ์ผ์ ์ฐ๋ค.
with open('data.txt', 'w') as file:
file.write('Hello')
2. JSON ํ์ผ ์ฝ๊ธฐ
import json
JSON ํ์ผ์ ์ฝ๊ณ ๋ฌธ์์ด์ ๋์ ๋๋ฆฌ๋ก ๋ณํ
json.loads(string): ๋์ ๋๋ฆฌ ๋ฐํ
def create_dict(filename):
with open(filename) as file:
json_string = file.read()
return json.loads(json_string)
JSON ํ์ผ์ ์ฝ๊ณ ๋์
๋๋ฆฌ๋ฅผ JSON ํํ์ ๋ฌธ์์ด๋ก ๋ณํ
json.dumps(dictionary): string ๋ฐํ
def create_json(dictionary, filename):
with open(filename, 'w') as file:
json_string = json.dumps(dictionary)
file.write(json_string)
3. CSV ํ์ผ ์ฝ๊ธฐ (Comma Seperated Value)
์ฝค๋ง ๋ง๊ณ ๋ค๋ฅธ ๊ตฌ๋ถ ๋ฌธ์๋ ์ฌ์ฉ ๊ฐ๋ฅ
๋ฐ์ดํฐ๊ฐ ,๊ฐ ํฌํจ๋ ๊ฒฝ์ฐ ""๋ก ๊ฐ์ธ๋ฉด ๋๋ค.
CSV ๋ถ๋ฌ์ค๊ธฐ
1. csv.reader(file, delimiter=','): reader๋ฉ์๋๋ฅผ ์ด์ฉํ์ฌ ๊ตฌ๋ถ์ ์ค์ ํ ๋ฐ์์ค๊ธฐ
2. for row in reader: ํ ์ค์ฉ ์ฝ๊ณ ์ฒ๋ฆฌํ๊ธฐ
# books.csv
Fundamentals,"Goswami, Jaideva",signal_processing,228,Wiley
Data Smart,"Foreman, John",data_science,235,Wiley
God,"Hawking, Stephen",mathematics,197,Penguin
SuperMan,"Dubner, Stephen",economics,179,HarperCollins
import csv
def book_info():
with open(filename) as file:
reader = csv.reader(file, delimiter=',')
for row in reader:
title=row[0]
author=row[1]
pages=row[3]
print("{} ({}): {}p".format(title, author, pages))
filename = 'books.csv'
book_info(filename)
CSV์ ํน์ง
1. json์ ๋น๊ตํด key๊ฐ์ ํ์๋กํ์ง ์์, ๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๋ ๋ฐ ์ฉ๋์ ์ ๊ฒ ์๋ชจํจ
# movies.csv
์์ด์ธ๋งจ,Iron Man,2008
๊ฒจ์ธ์๊ตญ,Frozen,2013
# movies.json
[{"ko": "์์ด์ธ๋งจ", "en": "Iron Man", "year": 2008},
{"ko": "๊ฒจ์ธ์๊ตญ, "en": "Frozen", "year": 2013}]
2. ๊ตฌ์กฐ๊ฐ ์ทจ์ฝํ๋ค.
๋ฐ์ดํฐ์ delimiter๊ฐ ํฌํจ๋์ด ์์ผ๋ฉด ๋ฐ์ดํฐ๊ฐ ์ฝ๊ฒ ์๋ชป ๋๋์ด์ง๋ค.
'๐ Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] iterable ๊ฐ์ฒด ์ ๋ฆฌ (๋ฌธ์์ด, ๋ฆฌ์ํธ, ๋์ ๋๋ฆฌ, ํํ, ์งํฉ) (0) | 2021.12.21 |
---|