Один из самых удобных способов записать данные это использование готовых форматов, такие как JSON или YAML.
Из плюсов такого подхода стоит отметить вот что:
🔸 готовый, повсеместно используемый и поддерживаемый формат
🔸 простой и понятный файл, удобочитаемый для человека
🔸 можно легко редактировать в любом текстовом редакторе без специальных программ и библиотек
Но есть и минусы
🔹 затраты времени при записи файла (кодирование данных в нужный формат строки)
🔹 затраты времени при чтении файла (декодирование данных в Python объекты)
🔹 размер файла увеличивается из-за разметки данных (скобки, запятые, переносы, отступы...)
🔹 перед записью все данные должны быть помещены в память в полном объёме (не всегда)
🔹 при чтении необходимо считать весь файл в память и только потом декодировать данные
Если нужно писать немного данных в несколько файлов, то затраты по времени не ощутимы. Обычно это файлы конфига или какие-либо метаданные. Это отличный вариант под такие задачи.
Есть и другой поход к записи файлов - это бинарные файлы. Используется, когда данных достаточно много и никто их не собирается читать глазками😳.
🔸 очень быстрая запись
🔸 чтение значительно быстрей чем JSON, YAML итд
🔸 размер файла значительно меньше, так как нет разметки
🔸 можно записывать данные по мере поступления не загружая всё в память
🔸 можно извлечь любую часть данных независимо
Из минусов
🔹 нужно определить свой формат записи данных (если не используете готовую спецификацию определённого формата)
🔹 не получится открыть файл и визуально понять что там записано, а для чтения файла потребуется знать его спецификацию.
🔹 не так-то просто создать такой файл без специальной библиотеки
В таком виде удобно записывать большой массив любых однородных данных. Например, мониторинг валютной биржи или кэшированная анимация 3D геометрии.
(Это не означает что нельзя записать данные разного типа, просто это будет не так удобно)
Представьте себе JPG-картинку. По сути это немного мета-информации и большой массив пикселей. Тоже самое со звуком или видео файлом. Поэтому, если вы попробуете открыть картинку в текстовом редакторе вы увидите что-то вроде такого
f15d cd29 a564 4578 ...
09e2 9bc4 a696 1253 ...
84e9 4de1 3b23 c24a ...
2534 5161 28e0 709d ...
...
Это и есть записанные байтики. И для их чтения требуется определённый софт который знает что с ними делать. Под каждый тип файла.
К чему это я? Читайте в следующем посте...
#tricks#basic
Planning to make full use of the Vaccinated Travel Lanes this holiday season, or heading for a staycation?
Don’t forget to go through the ‘Check and Protect’ checklist for a thorough #MozzieWipeout of your home before you head off! https://go.gov.sg/dengue-checklist
Sudden rain showers are common in Singapore, so if you leave your pails or plant pots where they can collect water, do pay extra attention and drain these containers if they have collected any water.
Here’s a checklist for a thorough #MozzieWipeout: https://go.gov.sg/dengue-checklist
Have you emptied out your flower pot plates after watering your plants today? These plates tend to collect water, and can become mosquito breeding habitats if left unattended. Be sure to add emptying out the flower pot plates to your “To-do List” after watering your plants! Here’s a checklist for a thorough #MozzieWipeout: https://go.gov.sg/dengue-checklist
The annual National Dengue Prevention Campaign was launched today, to rally everyone to take urgent action to prevent mosquito breeding and a possible surge in dengue cases, amidst the continued high Aedes aegypti mosquito population, and higher circulation of less common Dengue virus serotypes.
The fight against dengue involves all of us. Let’s step up dengue prevention by doing the #MozzieWipeout regularly. go.gov.sg/mozzieproof
Planning a staycation with your SingapoRediscover vouchers? Keep yourself and your loved ones safe by going through the ‘Check and Protect’ checklist for a thorough #MozzieWipeout before your stay! https://go.gov.sg/dengue-checklist
Staying home during this COVID-19 period has brought out the green thumb in many of us. And yet, with interest comes responsibility, too! Set a daily reminder to keep your plants nourished and your home protected from dengue too: https://go.gov.sg/dengue-checklist#MozzieWipeout
The gully traps in our homes are perfect for mosquito multiplication! Cover rarely used gully traps or install anti-mosquito valves, to prevent mosquito breeding. Here’s a ‘Check and Protect’ checklist for your thorough #MozzieWipeout today: https://go.gov.sg/dengue-checklist
Do you know where are the favourite places for mosquitoes to lay their eggs?
Pails, flower pot plates/trays and ornamental vases are some of the persistent mosquito breeding habitats in homes. It’s time to search for and destroy these breeding habitats! If you’re not sure how, get started here: https://go.gov.sg/dengue-checklist#MozzieWipeout
The number of weekly dengue cases has declined by more than 50% from its peak this year. However, a 12% increase in the Aedes aegypti mosquito population was detected in the last 3 weeks.
So let’s not let our guard down; continue doing the #MozzieWipeout at least once a week and taking protective actions (go.gov.sg/stopdenguenow). You can also get regular alerts on areas with higher Aedes mosquito population and dengue clusters on myENV app (www.nea.gov.sg/myENV) with this step-by-step guide!
Think it’s impossible for mosquito eggs to hatch in your dish tray, mere inches away from your cups and plates? It certainly isn’t. All mosquitoes need is a 20 cent-sized drop of water to breed. Time to do a thorough check in your house! #MozzieWipeouthttps://go.gov.sg/dengue-checklist
Besides doing the #MozzieWipeout, take these 3 simple actions to protect yourself and your loved ones, especially if you live in a dengue cluster area: Spray, Apply, Wear. More tips here: www.nea.gov.sg/stop-dengue