import json
try:
with open('contacts.json', 'r', encoding='utf-8') as f:
contacts = json.load(f)
except FileNotFoundError:
contacts = {}
print(f'Завантажено {len(contacts)} контактів')
name = input('Ім\'я нового контакту (Enter - пропустити): ')
if name:
phone = input('Телефон: ')
contacts[name] = phone
print('\nУсі контакти:')
for n, p in contacts.items():
print(f' {n}: {p}')
with open('contacts.json', 'w', encoding='utf-8') as f:
json.dump(contacts, f, ensure_ascii=False, indent=2)
import csv
# Записуємо дані
with open('sales.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['товар', 'кількість', 'ціна'])
writer.writerows([
['Ноутбук', 2, 45000],
['Мишка', 10, 800],
['Клавіатура', 5, 2500],
['Монітор', 3, 18000],
['Навушники', 8, 3500]
])
# Читаємо та аналізуємо
with open('sales.csv', 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
total = 0
max_price = 0
max_item = ''
count = 0
for row in reader:
summa = int(row['кількість']) * int(row['ціна'])
total += summa
count += 1
if int(row['ціна']) > max_price:
max_price = int(row['ціна'])
max_item = row['товар']
print(f'Загальна сума: {total} грн.')
print(f'Найдорожчий: {max_item} ({max_price} грн.)')
print(f'Середній чек: {total / count:.0f} грн.')
import json
import csv
def json_to_csv(json_file, csv_file):
with open(json_file, 'r', encoding='utf-8') as f:
data = json.load(f)
with open(csv_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)
print(f'{json_file} -> {csv_file}')
def csv_to_json(csv_file, json_file):
with open(csv_file, 'r', encoding='utf-8') as f:
data = list(csv.DictReader(f))
with open(json_file, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
print(f'{csv_file} -> {json_file}')
# Тест
students = [
{'ім\'я': 'Аня', 'вік': 20, 'оцінка': 95},
{'ім\'я': 'Борис', 'вік': 22, 'оцінка': 82},
{'ім\'я': 'Віка', 'вік': 21, 'оцінка': 90}
]
with open('students.json', 'w', encoding='utf-8') as f:
json.dump(students, f, ensure_ascii=False, indent=2)
json_to_csv('students.json', 'students.csv')
csv_to_json('students.csv', 'students_copy.json')