Один из самых удобных способов записать данные это использование готовых форматов, такие как 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
🌎 In the Namib Desert, the welwitschia plant survives for centuries with just two leaves that grow continuously, curling and splitting but never falling off—a marvel of resilience in extreme heat. ✨
#botany⚡#deserts⚡#adaptation
👉subscribe Interesting Planet
🌍 The desert climate zone covers about one-fifth of Earth's land, yet some deserts get colder than snowy regions—Antarctica is classified as the world's largest desert by climate. ✨
#climatezones⚡#deserts⚡#earth⚡#geography⚡#nature
👉subscribe Amazing Geography
👉more Channels
🌎 Antarctica is the coldest extreme climate zone, with an average winter temperature of about -60°C. The hottest zone is the Lut Desert in Iran, where ground temperatures have reached 80.8°C, the highest ever recorded on Earth. ✨
#climate⚡#extremes⚡#deserts⚡#antarctica
👉subscribe Interesting Planet
🌍 The Gobi Desert experiences freezing winters with temperatures dropping below –40°C, making it one of the few deserts known for both scorching heat and extreme cold. ✨
#deserts⚡#climate⚡#extremes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Earth holds the record for the highest known surface temperatures for a rocky planet in our Solar System, with some desert spots topping 56°C—hotter than the ground on Venus or Mars. ✨
#planet⚡#deserts⚡#extremes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Desert varnish is a thin, dark coating that forms on rocks in arid landscapes over thousands of years. It’s made from wind-blown clay and minerals, creating natural stone “paintings.” ✨
#deserts⚡#aridlandscapes⚡#geology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In the world’s subtropical climate zones, some deserts like the Sahara and Arabian receive less than 2 centimeters of rain a year—making them among the driest places on Earth. ✨
#climatezones⚡#deserts⚡#rainfall⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 In the Taklamakan Desert of China, some sand dunes reach up to 300 meters tall. Shifting winds keep these giant dunes moving, constantly reshaping the landscape year after year. ✨
#deserts⚡#dunes⚡#arid⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 In Australia’s Simpson Desert, certain red sand dunes can “move” up to a meter each year as winds slowly push millions of grains, gradually shifting entire hills across the arid landscape. ✨
#deserts⚡#dunes⚡#Australia⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Lut Desert in Iran holds the record for Earth’s hottest land temperature ever measured from space—an astonishing 80.8°C, far exceeding typical desert heat. ✨
#deserts⚡#temperature⚡#extremes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
In Death Valley’s Racetrack Playa, large rocks, some weighing hundreds of kilograms, move across the dry lake bed, leaving long tracks behind. This happens when a rare set of conditions align. First, rain fills the lake bed with a shallow layer of water. At night, the water freezes into thin sheets of ice. As the sun warms the ground, the ice breaks into large, floating panels. Light winds then push the ice, slowly moving the rocks across the playa. The tracks left behind can last for decades, creating unique patterns. This natural process has been understood by scientists and is one of the most fascinating geological phenomena.
🪨❄️🌞
[Read more]
@googlefactss
#Nature#WeirdFacts#Geography#DidYouKnow#Deserts#Science#Mystery
🌍 In some deserts, rare rain triggers bursts of wildflowers that cover the landscape in color for just a few days. Seeds can lie dormant for years, waiting for the right moisture to bloom. ✨
#deserts⚡#aridlandscapes⚡#wildflowers⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels