Один из самых удобных способов записать данные это использование готовых форматов, такие как 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
A dolphin can make about 700 to 1000 clicking sounds per second. The clicks come from deep inside the dolphin’s head, underneath the blowhole. Scientists call this area the phonic lips or sometimes “monkey lips.”
@googlefactss#mammals
Bats are the slowest reproducing mammals in the world for their size, and pregnancy is longer in bats than in other animals of their size.
@googlefactss#mammals
There are two main groups of bats: larger, Old World, fruit-eating mega bats (Megachiroptera) and microbats (Microchiroptera). Megabats are also known as fruit bats or flying foxes and typically live in warm climates. They use their large eyes to find food in the dark and they tend to roost in trees rather than in caves, crevices, or old buildings. Microbats are generally much smaller and use echolocation to find insects. Microbats are typically found all over the world, including the U.S. Not all megabats are larger than microbats.
@googlefactss#mammals#nowyouknow
A mother koala 🐨 will feed her baby her own feces known as pap. Baby koalas—or joeys—haven’t developed the intestinal bacteria 🦠 that help detoxify the highly poisonous eucalyptus leaves 🍃, which are a koala’s main diet. This process is crucial for their survival. ❤️
@googlefactss#animals#mammals
A mother orangutan 🦧 never puts her babies 👶 down and typically nurses them 🍼 for 6 to 9 years, which is the longest mother/child nursing dependence of any animal on earth! 🌍❤️
@googlefactss#animals#mammals
[read more...]
🌎 In the dense forests of Southeast Asia, the binturong uses its prehensile tail like a fifth limb—wrapping it around tree branches for balance and grip. This adaptation helps it nimbly move through the canopy and reach fruit high above the forest floor. ✨
#mammals⚡#adaptation⚡#rainforest
👉subscribe Interesting Planet
🌎 The silky anteater is the world’s smallest anteater, fitting in your hand! With dense golden fur and a prehensile tail, it climbs trees at night to slurp up ants, avoiding predators with its tiny size and camouflage. ✨
#mammals⚡#rainforest⚡#adaptation
👉subscribe Interesting Planet
🌎 In the remote forests of India, the Malabar giant squirrel can leap over 6 meters between trees. Its colorful fur blends red, purple, and orange tones, making it one of the world’s most striking mammals. ✨
#wildlife⚡#biodiversity⚡#mammals
👉subscribe Interesting Planet
🌎 In the icy landscapes of Greenland, musk oxen survive Arctic winters thanks to an incredibly dense undercoat called qiviut, which is eight times warmer than sheep’s wool. This soft fiber insulates these shaggy animals so well that snow won't melt on their backs, even in the harshest cold. ✨
#mammals⚡#adaptation⚡#arctic
👉subscribe Interesting Planet
There's an animal that smells like buttered popcorn. The binturong (Arctictis binturong), a Southeast Asian "bearcat," smells like buttered popcorn due to 2-acetyl-1-pyrroline (2-AP) in its urine, which it uses to mark territory. This chemical is the same aromatic compound produced when popcorn is popped. These arboreal, cat-like mammals are threatened by habitat loss.
@googlefactss#animals#mammals#bizarre
[read more....]
🌎 Every year, saiga antelopes in Central Asia undertake one of the largest mammal migrations, moving up to 1,200 kilometers across Kazakhstan and Russia. These critically endangered animals travel in herds of thousands to reach seasonal grazing areas, helping their calves survive harsh winters. ✨
#wildlife⚡#migration⚡#mammals
👉subscribe Interesting Planet
👉more Channels