Один из самых удобных способов записать данные это использование готовых форматов, такие как 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 single volcanic eruption can inject millions of tons of ash into the stratosphere, blocking sunlight and cooling global temperatures for months or even years after the disaster. ✨
#volcanoes⚡#climate⚡#hazards⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Mount Rainier in the United States is an active volcano capped with glaciers. Its ice stores enough water that a single eruption could trigger sudden, dangerous floods far downstream. ✨
#mountains⚡#volcanoes⚡#hazards⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Supercooled rain falls when liquid droplets stay below freezing but don’t turn to ice until they hit a surface. This rare weather event can glaze roads and trees in dangerous, clear ice. ✨
#meteorology⚡#precipitation⚡#hazards⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🪐 Asteroid (2015) BN509, a giant space rock measuring about 200 meters wide and 400 meters long, speeds past Earth with a shape resembling a giant peanut. Its close flyby in 2017 brought it within just 14 times the distance to the Moon, and radar imaging revealed its rapid rotation and elongated, tumbling motion—features that could make its path unpredictable if nudged by gravity. ✨
#asteroids⚡#hazards⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos
👉subscribe Universe Mysteries
👉more Channels
🪐 The asteroid (29075) 1950 DA stands out not only for its size but for its unique structure—it’s held together mostly by the tiny forces between individual grains, known as van der Waals forces, rather than by its own gravity. This means that if 1950 DA ever impacted Earth, its loosely-bound material could break apart differently than a solid rock, making its potential effects more unpredictable compared to typical asteroids. ✨
#asteroids⚡#hazards⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos
👉subscribe Universe Mysteries
🪐 The asteroid 1950 DA, about 1 kilometer wide, is hurtling through space with an orbit that brings it close to Earth every few decades. Scientists monitor it closely because its surface is so loosely held together by gravity that only tiny forces—like sunlight pressure—keep it from flying apart, making it a uniquely fragile but potentially dangerous near-Earth object. ✨
#asteroids⚡#hazards⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos
👉subscribe Universe Mysteries
🌍 Earthquakes under the ocean can create tsunamis—giant waves traveling at jet speed. A tsunami may cross an entire ocean before reaching land with just minutes’ warning. ✨
#tsunami⚡#earthquake⚡#hazards⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🪐 Asteroid (1862) Apollo is one of the first discovered "Apollo-type" near-Earth asteroids, regularly crossing Earth's orbit on its journey around the Sun. Measuring about 1.5 kilometers wide, Apollo's path is closely monitored because its changing orbit brings it close enough to qualify as potentially hazardous—a reminder of why astronomers track even ancient space rocks to protect our planet from unexpected encounters. ✨
#asteroids⚡#hazards⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2013, the small asteroid 2012 DA14, about 30 meters wide, passed just 27,700 kilometers above Earth—closer than many weather satellites. Unlike much larger objects, even an asteroid this size could cause massive regional destruction if it ever struck, which is why astronomers keep careful watch for these smaller, fast-moving near-Earth objects. ✨
#asteroids⚡#hazards⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Asteroid (2015) BP513 is a near-Earth object discovered in 2015, which measures around 440 meters across and has an orbit that occasionally brings it within a few lunar distances of our planet. While it poses no immediate threat, its path is tracked closely by astronomers, since an object of this size could cause severe regional damage if it ever collided with Earth—a reminder of why the study and monitoring of such asteroids are vital for planetary defense. ✨
#asteroids⚡#hazards⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Asteroid (86039) 1999 NC43 is a massive near-Earth object more than 2 kilometers wide that follows a path bringing it close to our planet's orbit. Its size means that if it ever collided with Earth, it could cause planet-wide devastation, so astronomers keep a careful watch on its movements using radar to track any changes in its trajectory. ✨
#asteroids⚡#hazards⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The asteroid (99942) Apophis isn’t the only space object that often makes headlines for threatening Earth—asteroid (4450) Pan crosses our planet's orbit several times each century and is classified as a "potentially hazardous asteroid." Pan is about 1.1 kilometers wide, and astronomers regularly track its path for any minor changes that could bring it closer, since an object of this size could cause widespread destruction if a collision ever occurred. ✨
#asteroids⚡#hazards⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels