Один из самых удобных способов записать данные это использование готовых форматов, такие как 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 sky over northern Norway, rare “polar stratospheric clouds” shine with vivid colors at twilight. These icy clouds form high above the Arctic, scattering sunlight into dazzling pastel waves—a fleeting phenomenon that can transform winter skies into a surreal rainbow spectacle. ✨
#atmosphere⚡#arctic⚡#phenomena
👉subscribe Interesting Planet
🌍 Some sandy coastlines can actually sing. In places like Oman and California, movement of millions of sand grains produces a deep hum or booming sound called "singing sands." ✨
#coast⚡#sand⚡#phenomena⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌎 In the Namib Desert, strange circular patches called “fairy circles” appear in the grass, forming patterns seen from the air. Scientists suspect termites or plant competition cause these barren rings, which can measure 2 to 15 meters wide and last for decades. ✨
#desert⚡#phenomena⚡#patterns
👉subscribe Interesting Planet
👉more Channels
🌎 Red rain fell in the Indian state of Kerala in 2001, coloring streets and clothing. Scientists found the cause was airborne spores from local algae cells. Some showers were bright red for up to two months. ✨
#phenomena⚡#weather⚡#algae
👉subscribe Interesting Planet
👉more Channels
"Nunca habíamos visto nada igual..."
Algo aterrador está sucediendo en Estados Unidos (2025)
Únase a nosotros: https://anon.news
🔘En este video, el mundo quedó atónito ante la repentina aparición de un elegante monolito metálico en los remotos desiertos de Utah.
Alto y silencioso, el objeto guardaba un asombroso parecido con los monolitos de 2001: Odisea del Espacio, y luego, con la misma incógnita, desapareció.
Desde entonces, han aparecido docenas de estructuras similares en lugares de todo el mundo, desde las montañas nevadas de Rumania hasta las playas de California, las selvas de Colombia y los tejados de las ciudades europeas.
¿Son instalaciones artísticas, engaños elaborados o algo más enigmático?
Cada monolito parece surgir sin previo aviso, a menudo en lugares de difícil acceso, y sin que nadie se atribuya la responsabilidad.
Algunos son espejados y minimalistas; otros están grabados con símbolos crípticos.
El fenómeno ha desatado la intriga mundial, generando teorías de conspiración, videos virales y un auge en el debate especulativo sobre la vida extraterrestre, las sociedades secretas y la conciencia colectiva.
#unexplained#strange#phenomena
@EndTimesProductions@Jaymez
🌎 Nature's own "blood rain" sometimes showers the Earth! This rare phenomenon happens when winds lift red Sahara dust into rainclouds—turning rainwater a rusty red as it falls. ✨
#phenomena⚡#weather⚡#Sahara
👉subscribe Interesting Planet
🪐 In the distant galaxy MACS J1149+2223, astronomers have witnessed an unusual event called a "refreshed" supernova, where a massive star's explosion appeared to brighten twice, likely caused by material from the original blast catching up to the shockwave years later. This rare phenomenon allows scientists to observe the same supernova event evolving in real time, a cosmic encore not often seen in the universe. ✨
#supernova⚡#galaxy⚡#phenomena⚡#nasa⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In the galaxy SDSS J135154.46+132719.1, astronomers have observed a striking phenomenon: a supermassive black hole that was caught being "kicked" out of its galaxy at nearly 7.5 million kilometers per hour. This cosmic eviction is thought to be caused by the merged black holes’ gravitational waves pushing the giant object away—an extreme event where the very heart of a galaxy is flung into intergalactic space. ✨
#phenomena⚡#galaxy⚡#blackhole⚡#nasa⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In the star system V Hydrae, located about 1,300 light-years away in Hydra, astronomers have observed mysterious, high-speed "bullets" of hot gas being violently ejected from the dying red giant star. These jets blast out at speeds up to 800,000 kilometers per hour and appear at regular intervals, creating bizarre patterns of moving material that are among the strangest cosmic outflows seen in our galaxy. ✨
#phenomena⚡#stars⚡#jets⚡#nasa⚡#galaxy⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the galaxy NGC 1999, astronomers observed a mysterious, dark patch once believed to be a dense cloud of cosmic dust blocking light. However, further study revealed this region is actually a rare "hole" in the nebula—an empty cavity punched through the glowing gas by powerful stellar winds from young, massive stars, making it a striking example of cosmic sculpting at work. ✨
#nebula⚡#phenomena⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In the galaxy NGC 4845, astronomers observed a strange cosmic event where a giant cloud of gas was ripped apart and swallowed by a supermassive black hole. This violent feast caused a sudden, bright flare of X-rays—evidence of what's called a "tidal disruption event," when the intense gravity tears matter apart and feeds it to the black hole, lighting up the galaxy for months. ✨
#phenomena⚡#galaxy⚡#xray⚡#nasa⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🌎 The mysterious Hessdalen lights regularly appear in a remote Norwegian valley as glowing orbs floating and darting across the sky. Scientists have observed these lights since the 1930s and believe they may be caused by ionized dust or chemical reactions in the air, but their true origin remains unexplained. Some lights last for hours, and over 60 sightings were recorded in just one month during the 1980s. ✨
#hessdalen⚡#phenomena⚡#norway
👉subscribe Interesting Planet
👉more Channels