Один из самых удобных способов записать данные это использование готовых форматов, такие как 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
🪐 The exoplanet Kepler-438b, orbiting a red dwarf star about 470 light-years from Earth, is one of the most Earth-like worlds found in terms of size and temperature. Scientists have carefully measured its position in the “habitable zone”—the region around a star where liquid water might exist, a key ingredient scientists believe is necessary for life as we know it. ✨
#aliens⚡#exoplanets⚡#habitability⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Astronomers have pinpointed the exoplanet LP 890-9 c, located about 105 light-years away in the constellation Eridanus, as one of the most promising places for life outside our solar system. This rocky world orbits within its star’s habitable zone—the region where temperatures could allow liquid water to persist, making it a key target in the search for planets that might support life as we know it. ✨
#exoplanets⚡#habitability⚡#astrobiology⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Astronomers have discovered that the exoplanet Gliese 486 b, about 26 light-years away in the constellation Virgo, is a rocky world with surface temperatures hot enough to melt lead. Even though it's likely too warm for life as we know it, its firm, Earth-like surface and relatively close distance make it an important candidate for studying rocky planets outside our solar system—and for searching how and where life might survive under extreme conditions. ✨
#exoplanets⚡#life⚡#habitability⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Around the distant red dwarf star LHS 1140, about 49 light-years from Earth, astronomers have discovered a rocky exoplanet called LHS 1140 b that sits right in the star’s “habitable zone”—the area where temperatures could allow liquid water to exist. Recent observations suggest its atmosphere may still be intact, making LHS 1140 b one of the most promising known worlds for the search for life beyond our solar system. ✨
#exoplanets⚡#habitability⚡#discovery⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Beyond our solar system, two intriguing exoplanets orbit the star Kepler-62: Kepler-62e and Kepler-62f. Both are considered "super-Earths" (planets larger than Earth but smaller than Neptune) and sit inside their star’s habitable zone, a region where temperatures might allow water to exist as a liquid—a key ingredient for life as we know it. ✨
#exoplanets⚡#habitability⚡#water⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Orbiting the cool red dwarf star Ross 128, about 11 light-years away, the exoplanet Ross 128 b is roughly Earth-sized and lies in its star’s temperate zone, where conditions might allow liquid water. Although Ross 128 is much dimmer than the Sun, its calm nature means less intense flares, making Ross 128 b an especially intriguing place in our search for potentially habitable worlds beyond our solar system. ✨
#exoplanets⚡#habitability⚡#water⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Astronomers have identified Kepler-442b, an exoplanet about 1,200 light-years away in the constellation Lyra, as a strong candidate for hosting life. This rocky world orbits in its star’s habitable zone—a region where temperatures could allow liquid water—and is just slightly larger than Earth, making it an intriguing example of a real planet with conditions that might one day support living organisms. ✨
#exoplanets⚡#habitability⚡#Kepler442b⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Scientists have identified the exoplanet Gliese 581d, orbiting a red dwarf star about 20 light-years away, as one of the earliest potentially habitable worlds outside our solar system. Gliese 581d lies within its star's habitable zone, where temperatures might allow liquid water to exist, making it a key target in the search for life beyond Earth. ✨
#exoplanet⚡#habitability⚡#water⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Just 39 light-years away, the exoplanet TRAPPIST-1e circles its cool red dwarf star in the habitable zone, where temperatures might allow liquid water. Scientists have found that TRAPPIST-1e has a rocky surface and, unlike some of its neighbors, could have the right conditions for life as we know it. ✨
#exoplanet⚡#habitability⚡#TRAPPIST1e⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Saturn’s moon Titan is one of the most intriguing places in the solar system where life could exist because it has lakes and rivers of liquid methane and ethane—chemicals similar to gasoline on Earth. While it’s far too cold for liquid water, scientists are captivated by the idea that life, if it ever formed there, would be fundamentally different from anything on our planet. ✨
#Titan⚡#methane⚡#habitability⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Astronomers have found signs that Uranus’s moon Miranda may hide a subsurface ocean of liquid water beneath its fractured, icy crust. The unique patterns of ridges and canyons on Miranda, revealed by Voyager 2, suggest internal heat could provide the conditions needed for liquid water—a key ingredient for life—even on this tiny, distant world. ✨
#Miranda⚡#oceanworlds⚡#habitability⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels