JSON๊ณผ CSV
In Python JSON๊ณผ CSV ๋ฐ์ดํฐ๋ฅผ ๋ค๋ฃจ๋ Methode lernen wir. ์ด ๋ ๊ฐ์ง๋ ๊ฐ์ฅ ๋๋ฆฌ ์ฌ์ฉ๋๋ ๋ฐ์ดํฐ ๊ตํ ํ์.
JSON ๋ค๋ฃจ๊ธฐ ๐ฆโ
JSON(JavaScript Object Notation)์ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๊ณ ์ ์กํ๋ ๊ฒฝ๋ ํ์.
Grundlegend ์ฌ์ฉ๋ฒโ
import json
# Python ๊ฐ์ฒด โ JSON ๋ฌธ์์ด
data = {
'name': 'ํ๊ธธ๋',
'age': 30,
'city': '์์ธ',
'hobbies': ['๋
์', '๋ฑ์ฐ', '์๋ฆฌ']
}
json_string = json.dumps(data)
print(json_string)
# {"name": "ํ๊ธธ๋", "age": 30, "city": "์์ธ", "hobbies": ["๋
์", "๋ฑ์ฐ", "์๋ฆฌ"]}
# JSON ๋ฌธ์์ด โ Python ๊ฐ์ฒด
parsed_data = json.loads(json_string)
print(parsed_data['name']) # ํ๊ธธ๋
ํ์ผ๋ก ์ ์ฅํ๊ณ ์ฝ๊ธฐโ
import json
# JSON ํ์ผ๋ก ์ ์ฅ
data = {
'users': [
{'id': 1, 'name': '๊น์ฒ ์', 'email': 'kim@example.com'},
{'id': 2, 'name': '์ด์ํฌ', 'email': 'lee@example.com'},
]
}
with open('users.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# JSON Dateien lesen
with open('users.json', 'r', encoding='utf-8') as f:
loaded_data = json.load(f)
print(loaded_data)
JSON ํฌ๋งทํ ์ต์ โ
import json
data = {'name': 'ํ๊ธธ๋', 'age': 30, 'skills': ['Python', 'JavaScript']}
# ๋ค์ฌ์ฐ๊ธฐ ์์ (์์ถ)
compact = json.dumps(data)
print(compact)
# {"name": "ํ๊ธธ๋", "age": 30, "skills": ["Python", "JavaScript"]}
# ๋ค์ฌ์ฐ๊ธฐ 2์นธ (์ฝ๊ธฐ ์ฝ๊ฒ)
pretty = json.dumps(data, indent=2, ensure_ascii=False)
print(pretty)
# {
# "name": "ํ๊ธธ๋",
# "age": 30,
# "skills": [
# "Python",
# "JavaScript"
# ]
# }
# ํค ์ ๋ ฌ
sorted_json = json.dumps(data, sort_keys=True, indent=2, ensure_ascii=False)
print(sorted_json)
๋ณต์กํ ๋ฐ์ดํฐ ํ์ ์ฒ๋ฆฌโ
import json
from datetime import datetime
from decimal import Decimal
class DateTimeEncoder(json.JSONEncoder):
"""datetime์ JSON์ผ๋ก ์ง๋ ฌํ"""
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, Decimal):
return float(obj)
return super().default(obj)
# ์ฌ์ฉ Beispiel
data = {
'timestamp': datetime.now(),
'amount': Decimal('123.45')
}
json_string = json.dumps(data, cls=DateTimeEncoder, indent=2)
print(json_string)
CSV ๋ค๋ฃจ๊ธฐ ๐โ
CSV(Comma-Separated Values)๋ ํ ํ์ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๋ ๊ฐ๋จํ ํ์.
Grundlegend CSV ์ฐ๊ธฐโ
import csv
# CSV Dateien schreiben
data = [
['์ด๋ฆ', '๋์ด', '๋์'],
['ํ๊ธธ๋', 30, '์์ธ'],
['๊น์ฒ ์', 25, '๋ถ์ฐ'],
['์ด์ํฌ', 28, '๋๊ตฌ']
]
with open('users.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(data)
CSV ์ฝ๊ธฐโ
import csv
# CSV Dateien lesen
with open('users.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
# ['์ด๋ฆ', '๋์ด', '๋์']
# ['ํ๊ธธ๋', '30', '์์ธ']
# ...
DictReader: ๋์ ๋๋ฆฌ๋ก ์ฝ๊ธฐโ
import csv
# ํค๋๋ฅผ ํค๋ก ์ฌ์ฉํ์ฌ ์ฝ๊ธฐ
with open('users.csv', 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['์ด๋ฆ']}์ {row['๋์ด']}์ธ์ด๊ณ {row['๋์']}์ ์ฝ๋๋ค.")
# ํ๊ธธ๋์ 30์ธ์ด๊ณ ์์ธ์ ์ฝ๋๋ค.
# ๊น์ฒ ์๋ 25์ธ์ด๊ณ ๋ถ์ฐ์ ์ฝ๋๋ค.
DictWriter: ๋์ ๋๋ฆฌ๋ก ์ฐ๊ธฐโ
import csv
# ๋์
๋๋ฆฌ ๋ฐ์ดํฐ๋ฅผ CSV๋ก ์ ์ฅ
users = [
{'name': 'ํ๊ธธ๋', 'age': 30, 'city': '์์ธ'},
{'name': '๊น์ฒ ์', 'age': 25, 'city': '๋ถ์ฐ'},
{'name': '์ด์ํฌ', 'age': 28, 'city': '๋๊ตฌ'}
]
with open('users_dict.csv', 'w', newline='', encoding='utf-8') as f:
fieldnames = ['name', 'age', 'city']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader() # ํค๋ ์ฐ๊ธฐ
writer.writerows(users) # ๋ชจ๋ ํ ์ฐ๊ธฐ
CSV ์ต์ โ
import csv
# ๊ตฌ๋ถ์ ๋ณ๊ฒฝ (ํญ, ์ธ๋ฏธ์ฝ๋ก ๋ฑ)
with open('data.tsv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerow(['์ด๋ฆ', '๋์ด'])
writer.writerow(['ํ๊ธธ๋', 30])
# ์ธ์ฉ ์คํ์ผ
with open('quoted.csv', 'w', newline='', encoding='utf-8') as f:
# QUOTE_ALL: ๋ชจ๋ ํ๋๋ฅผ ์ธ์ฉ
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
writer.writerow(['์ด๋ฆ', '๋์ด'])
# QUOTE_MINIMAL: ํ์ํ ๊ฒฝ์ฐ๋ง ์ธ์ฉ (Grundlegend๊ฐ)
writer = csv.writer(f, quoting=csv.QUOTE_MINIMAL)
writer.writerow(['ํ๊ธธ๋', 30])
์ค์ Beispiel ๐กโ
Beispiel 1: API ์๋ต ํ์ฑโ
import json
import urllib.request
def fetch_and_parse_json(url):
"""JSON API ํธ์ถ ๋ฐ ํ์ฑ"""
try:
with urllib.request.urlopen(url) as response:
data = response.read()
return json.loads(data)
except Exception as e:
print(f'์๋ฌ ๋ฐ์: {e}')
return None
# ์ฌ์ฉ Beispiel (์ค์ API ์ฌ์ฉ)
# url = 'https://api.example.com/users'
# users = fetch_and_parse_json(url)
# ๋ก์ปฌ JSON Dateien lesen Beispiel
def load_user_data(filename):
"""์ฌ์ฉ์ ๋ฐ์ดํฐ ๋ก๋"""
try:
with open(filename, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
print(f'ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค: {filename}')
return []
except json.JSONDecodeError as e:
print(f'JSON ํ์ฑ ์๋ฌ: {e}')
return []
# users = load_user_data('users.json')
# for user in users:
# print(f"{user['name']}: {user['email']}")
Beispiel 2: ์ค์ ํ์ผ ๊ด๋ฆฌโ
import json
from pathlib import Path
class Config:
"""JSON ์ค์ ํ์ผ ๊ด๋ฆฌ์"""
def __init__(self, config_file='config.json'):
self.config_file = Path(config_file)
self.data = self.load()
def load(self):
"""์ค์ ํ์ผ ๋ก๋"""
if self.config_file.exists():
with open(self.config_file, 'r', encoding='utf-8') as f:
return json.load(f)
return self.get_default()
def save(self):
"""์ค์ ํ์ผ ์ ์ฅ"""
with open(self.config_file, 'w', encoding='utf-8') as f:
json.dump(self.data, f, indent=2, ensure_ascii=False)
def get(self, key, default=None):
"""์ค์ ๊ฐ ๊ฐ์ ธ์ค๊ธฐ"""
return self.data.get(key, default)
def set(self, key, value):
"""์ค์ ๊ฐ ์ค์ ํ๊ธฐ"""
self.data[key] = value
self.save()
def get_default(self):
"""Grundlegend ์ค์ """
return {
'app_name': 'MyApp',
'version': '1.0.0',
'debug': False,
'max_connections': 100
}
# ์ฌ์ฉ Beispiel
config = Config()
print(f"์ฑ ์ด๋ฆ: {config.get('app_name')}")
config.set('debug', True)
print(f"๋๋ฒ๊ทธ ๋ชจ๋: {config.get('debug')}")
Beispiel 3: CSV์์ JSON์ผ๋ก ๋ณํโ
import csv
import json
def csv_to_json(csv_file, json_file):
"""CSV ํ์ผ์ JSON์ผ๋ก ๋ณํ"""
data = []
with open(csv_file, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
# ์ซ์ ํ์
๋ณํ
for key, value in row.items():
if value.isdigit():
row[key] = int(value)
elif value.replace('.', '', 1).isdigit():
row[key] = float(value)
data.append(row)
with open(json_file, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f'{csv_file} โ {json_file} ๋ณํ ์๋ฃ')
return data
# ์ฌ์ฉ Beispiel
# data = csv_to_json('users.csv', 'users.json')
Beispiel 4: JSON์์ CSV๋ก ๋ณํโ
import json
import csv
def json_to_csv(json_file, csv_file):
"""JSON ํ์ผ์ CSV๋ก ๋ณํ"""
with open(json_file, 'r', encoding='utf-8') as f:
data = json.load(f)
if not data:
print('๋ฐ์ดํฐ๊ฐ ๋น์ด์์ต๋๋ค')
return
# ์ฒซ ๋ฒ์งธ ํญ๋ชฉ์์ ํค ์ถ์ถ
if isinstance(data, list):
fieldnames = list(data[0].keys())
else:
# ๋จ์ผ ๊ฐ์ฒด์ธ ๊ฒฝ์ฐ
data = [data]
fieldnames = list(data[0].keys())
with open(csv_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
print(f'{json_file} โ {csv_file} ๋ณํ ์๋ฃ')
# ์ฌ์ฉ Beispiel
# json_to_csv('users.json', 'users_output.csv')
Beispiel 5: ์์ ๋ฐ์ดํฐ ์ฒ๋ฆฌ (CSV ์ฌ์ฉ)โ
import csv
from collections import defaultdict
class SalesAnalyzer:
"""ํ๋งค ๋ฐ์ดํฐ ๋ถ์๊ธฐ"""
def __init__(self, csv_file):
self.data = self.load_data(csv_file)
def load_data(self, csv_file):
"""CSV ๋ฐ์ดํฐ ๋ก๋"""
data = []
with open(csv_file, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
# ์ซ์ ๋ณํ
row['amount'] = float(row['amount'])
row['quantity'] = int(row['quantity'])
data.append(row)
return data
def total_sales(self):
"""์ด ๋งค์ถ"""
return sum(item['amount'] for item in self.data)
def sales_by_product(self):
"""์ ํ๋ณ ๋งค์ถ"""
sales = defaultdict(float)
for item in self.data:
sales[item['product']] += item['amount']
return dict(sales)
def top_products(self, n=5):
"""์์ N๊ฐ ์ ํ"""
sales = self.sales_by_product()
sorted_products = sorted(sales.items(), key=lambda x: x[1], reverse=True)
return sorted_products[:n]
def generate_report(self, output_file):
"""๋ฆฌํฌํธ ์์ฑ"""
report = {
'total_sales': self.total_sales(),
'product_count': len(self.sales_by_product()),
'top_products': [
{'product': name, 'sales': amount}
for name, amount in self.top_products()
]
}
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(report, f, indent=2, ensure_ascii=False)
return report
# ์ฌ์ฉ Beispiel (CSV ํ์ผ ์์ฑ)
sample_data = [
['product', 'quantity', 'amount'],
['๋
ธํธ๋ถ', 5, 5000000],
['๋ง์ฐ์ค', 20, 500000],
['ํค๋ณด๋', 15, 1500000],
['๋
ธํธ๋ถ', 3, 3000000],
]
with open('sales.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(sample_data)
# analyzer = SalesAnalyzer('sales.csv')
# print(f'์ด ๋งค์ถ: {analyzer.total_sales():,}์')
# print(f'์ ํ๋ณ ๋งค์ถ: {analyzer.sales_by_product()}')
# analyzer.generate_report('sales_report.json')
Beispiel 6: ์ค์ฒฉ๋ JSON ์ฒ๋ฆฌโ
import json
def flatten_json(nested_json, parent_key='', separator='_'):
"""์ค์ฒฉ๋ JSON์ ํํํ"""
items = []
for key, value in nested_json.items():
new_key = f'{parent_key}{separator}{key}' if parent_key else key
if isinstance(value, dict):
items.extend(flatten_json(value, new_key, separator).items())
elif isinstance(value, list):
for i, item in enumerate(value):
if isinstance(item, dict):
items.extend(flatten_json(item, f'{new_key}_{i}', separator).items())
else:
items.append((f'{new_key}_{i}', item))
else:
items.append((new_key, value))
return dict(items)
# ์ฌ์ฉ Beispiel
nested_data = {
'name': 'ํ๊ธธ๋',
'address': {
'city': '์์ธ',
'street': '๊ฐ๋จ๋๋ก',
'zipcode': '12345'
},
'phones': [
{'type': 'home', 'number': '02-1234-5678'},
{'type': 'mobile', 'number': '010-1234-5678'}
]
}
flat = flatten_json(nested_data)
print(json.dumps(flat, indent=2, ensure_ascii=False))
Beispiel 7: CSV ๋ฐ์ดํฐ ํํฐ๋ง ๋ฐ ์ ๋ ฌโ
import csv
class CSVProcessor:
"""CSV ๋ฐ์ดํฐ ์ฒ๋ฆฌ๊ธฐ"""
def __init__(self, filename):
self.filename = filename
self.data = self.load()
def load(self):
"""CSV ๋ก๋"""
with open(self.filename, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
return list(reader)
def filter(self, condition):
"""์กฐ๊ฑด์ ๋ง๋ ํ ๋ง ํํฐ๋ง"""
return [row for row in self.data if condition(row)]
def sort(self, key, reverse=False):
"""์ ๋ ฌ"""
return sorted(self.data, key=lambda x: x[key], reverse=reverse)
def save(self, data, output_file):
"""๊ฒฐ๊ณผ ์ ์ฅ"""
if not data:
print('์ ์ฅํ ๋ฐ์ดํฐ๊ฐ ์์ต๋๋ค')
return
fieldnames = list(data[0].keys())
with open(output_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
print(f'{output_file} ์ ์ฅ ์๋ฃ')
# ์ฌ์ฉ Beispiel (์ํ CSV ์์ฑ)
sample_data = [
['name', 'age', 'city', 'salary'],
['ํ๊ธธ๋', '30', '์์ธ', '50000'],
['๊น์ฒ ์', '25', '๋ถ์ฐ', '40000'],
['์ด์ํฌ', '35', '์์ธ', '60000'],
['๋ฐ๋ฏผ์', '28', '๋๊ตฌ', '45000'],
]
with open('employees.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(sample_data)
# processor = CSVProcessor('employees.csv')
# ์์ธ์ ์ฌ๋ ์ง์๋ง ํํฐ๋ง
# seoul_employees = processor.filter(lambda row: row['city'] == '์์ธ')
# processor.save(seoul_employees, 'seoul_employees.csv')
# ๋์ด๋ก ์ ๋ ฌ
# sorted_by_age = processor.sort('age', reverse=True)
# processor.save(sorted_by_age, 'employees_sorted.csv')
Beispiel 8: JSON ์คํค๋ง ๊ฒ์ฆโ
import json
class JSONValidator:
"""๊ฐ๋จํ JSON ์คํค๋ง ๊ฒ์ฆ๊ธฐ"""
@staticmethod
def validate_user(data):
"""์ฌ์ฉ์ ๋ฐ์ดํฐ ๊ฒ์ฆ"""
required_fields = ['name', 'email', 'age']
errors = []
# ํ์ ํ๋ ํ์ธ
for field in required_fields:
if field not in data:
errors.append(f'ํ์ ํ๋ ๋๋ฝ: {field}')
# ํ์
ํ์ธ
if 'name' in data and not isinstance(data['name'], str):
errors.append('name์ ๋ฌธ์์ด์ด์ด์ผ ')
if 'age' in data:
try:
age = int(data['age'])
if age < 0 or age > 150:
errors.append('age๋ 0-150 ์ฌ์ด์ฌ์ผ ')
except ValueError:
errors.append('age๋ ์ซ์์ฌ์ผ ')
if 'email' in data and '@' not in data['email']:
errors.append('์ ํจํ์ง ์์ ์ด๋ฉ์ผ')
return len(errors) == 0, errors
@staticmethod
def validate_batch(data_list):
"""์ฌ๋ฌ ๋ฐ์ดํฐ ๊ฒ์ฆ"""
results = []
for i, data in enumerate(data_list):
is_valid, errors = JSONValidator.validate_user(data)
results.append({
'index': i,
'valid': is_valid,
'errors': errors,
'data': data
})
return results
# ์ฌ์ฉ Beispiel
users = [
{'name': 'ํ๊ธธ๋', 'email': 'hong@example.com', 'age': 30},
{'name': '๊น์ฒ ์', 'email': 'invalid-email', 'age': 25},
{'email': 'lee@example.com', 'age': 28}, # name ๋๋ฝ
{'name': '๋ฐ๋ฏผ์', 'email': 'park@example.com', 'age': 200}, # ์๋ชป๋ age
]
results = JSONValidator.validate_batch(users)
for result in results:
print(f"\nํญ๋ชฉ {result['index']}:")
if result['valid']:
print(' โ ์ ํจ')
else:
print(' โ ์ ํจํ์ง ์์')
for error in result['errors']:
print(f' - {error}')
Beispiel 9: ๋์ฉ๋ JSON ์คํธ๋ฆฌ๋ฐโ
import json
def process_large_json_file(filename):
"""๋์ฉ๋ JSON ํ์ผ์ ์ฒญํฌ ๋จ์๋ก ์ฒ๋ฆฌ"""
with open(filename, 'r', encoding='utf-8') as f:
# JSON ๋ฐฐ์ด์ ์คํธ๋ฆฌ๋ฐ์ผ๋ก ์ฒ๋ฆฌ
decoder = json.JSONDecoder()
buffer = ''
for line in f:
buffer += line
try:
# JSON ๊ฐ์ฒด ํ์ฑ ์๋
obj, index = decoder.raw_decode(buffer)
yield obj
# ํ์ฑ๋ ๋ถ๋ถ ์ ๊ฑฐ
buffer = buffer[index:].lstrip()
except json.JSONDecodeError:
# ์์ง ์์ ํ ๊ฐ์ฒด๊ฐ ์๋, ๊ณ์ ์ฝ๊ธฐ
continue
# ์ฌ์ฉ Beispiel
# for item in process_large_json_file('large_data.json'):
# process_item(item)
Beispiel 10: CSV์ JSON ํตํฉ ๋ฐ์ดํฐ ๊ด๋ฆฌโ
import csv
import json
from pathlib import Path
class DataManager:
"""CSV์ JSON์ ํตํฉ ๊ด๋ฆฌํ๋ Klasse"""
def __init__(self, data_dir='data'):
self.data_dir = Path(data_dir)
self.data_dir.mkdir(exist_ok=True)
def save(self, data, filename, format='json'):
"""๋ฐ์ดํฐ ์ ์ฅ (JSON ๋๋ CSV)"""
filepath = self.data_dir / filename
if format == 'json':
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
elif format == 'csv':
if not data:
return
with open(filepath, 'w', newline='', encoding='utf-8') as f:
if isinstance(data[0], dict):
writer = csv.DictWriter(f, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)
else:
writer = csv.writer(f)
writer.writerows(data)
print(f'{filepath} ์ ์ฅ ์๋ฃ')
def load(self, filename):
"""๋ฐ์ดํฐ ๋ก๋ (์๋ ํ์ ๊ฐ์ง)"""
filepath = self.data_dir / filename
if not filepath.exists():
print(f'ํ์ผ์ด ์์ต๋๋ค: {filepath}')
return None
# ํ์ฅ์๋ก ํ์ ํ๋จ
if filepath.suffix == '.json':
with open(filepath, 'r', encoding='utf-8') as f:
return json.load(f)
elif filepath.suffix == '.csv':
with open(filepath, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
return list(reader)
return None
def convert(self, input_file, output_file):
"""ํ์ผ ํ์ ๋ณํ"""
data = self.load(input_file)
if data is None:
return
output_format = Path(output_file).suffix[1:] # .json โ json
self.save(data, output_file, format=output_format)
print(f'{input_file} โ {output_file} ๋ณํ ์๋ฃ')
# ์ฌ์ฉ Beispiel
manager = DataManager()
# JSON ์ ์ฅ
users = [
{'id': 1, 'name': 'ํ๊ธธ๋', 'age': 30},
{'id': 2, 'name': '๊น์ฒ ์', 'age': 25},
]
manager.save(users, 'users.json', format='json')
# CSV ์ ์ฅ
manager.save(users, 'users.csv', format='csv')
# ๋ก๋
loaded_users = manager.load('users.json')
print(loaded_users)
# ๋ณํ
# manager.convert('users.json', 'users_converted.csv')
Hรคufig gestellte Fragen โโ
Q1: JSON์์ ํ๊ธ์ด \uXXXX๋ก ํ์๋๋ ๋ฌธ์ ๋?โ
import json
data = {'name': 'ํ๊ธธ๋'}
# ๋์จ: \uXXXX๋ก ์ธ์ฝ๋ฉ
json_str = json.dumps(data)
print(json_str) # {"name": "\ud64d\uae38\ub3d9"}
# ์ข์: ํ๊ธ ๊ทธ๋๋ก ์ ์ง
json_str = json.dumps(data, ensure_ascii=False)
print(json_str) # {"name": "ํ๊ธธ๋"}
Q2: CSV์์ ์ค๋ฐ๊ฟ์ด ์๋ ๋ฐ์ดํฐ๋ฅผ ์ฒ๋ฆฌํ๋ Methode์?โ
import csv
# ์ค๋ฐ๊ฟ์ด ํฌํจ๋ ๋ฐ์ดํฐ
data = [
['name', 'description'],
['Product A', 'This is\na multi-line\ndescription'],
]
# CSV๋ก ์ ์ฅ (์๋์ผ๋ก ์ธ์ฉ ์ฒ๋ฆฌ)
with open('products.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(data)
# ์ฝ์ ๋๋ ์๋์ผ๋ก ์ฒ๋ฆฌ
with open('products.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
Q3: JSON์ ์ฃผ์์ ์ถ๊ฐํ ์ ์๋์?โ
# JSON ํ์ค์ ์ฃผ์์ ์ง์ํ์ง ์์ง๋ง,
# ๋ฐ์ดํฐ์ _comment ํ๋๋ฅผ ์ถ๊ฐํ ์ ์์ต๋๋ค
config = {
'_comment': '์ด๊ฒ์ ์ค์ ํ์ผ',
'debug': True,
'max_connections': 100,
'database': {
'_comment': '๋ฐ์ดํฐ๋ฒ ์ด์ค ์ค์ ',
'host': 'localhost',
'port': 5432
}
}
# ๋๋ JSONC, JSON5 ๊ฐ์ ํ์ฅ ํ์ ์ฌ์ฉ
Q4: CSV ์ฒซ ์ค์ด ํค๋๊ฐ ์๋ ๋๋?โ
import csv
# ํค๋ ์ง์ ์ง์
with open('no_header.csv', 'r', encoding='utf-8') as f:
reader = csv.DictReader(f, fieldnames=['name', 'age', 'city'])
for row in reader:
print(row)