Один из самых удобных способов записать данные это использование готовых форматов, такие как 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
🌎 Hidden in the vast cosmic darkness, rogue planets drift alone through space without orbiting any star. These “orphan worlds” form when gravitational forces eject young planets from their home systems. Some estimates suggest our galaxy may contain more rogue planets than stars. ✨
#universe⚡#astronomy⚡#exoplanets
👉subscribe Interesting Planet
🌎 Some distant planets, called rogue planets, drift through space unattached to any star. Astronomers estimate there could be billions of these planets in our galaxy alone. ✨
#astronomy⚡#exoplanets⚡#cosmos
👉subscribe Interesting Planet
👉more Channels
🌎 In 2016, astronomers discovered TRAPPIST-1, a star system 40 light-years away with seven Earth-sized planets. Three orbit in the "habitable zone," where liquid water could exist—making it one of the most promising sites for searching for alien life beyond our solar system. ✨
#astronomy⚡#exoplanets⚡#habitable
👉subscribe Interesting Planet
🪐 The ultra-dense pulsar PSR B1257+12, located in the constellation Virgo about 2,300 light-years from Earth, hosts the first confirmed exoplanets ever discovered. These three worlds—each orbiting this spinning neutron star—endure intense radiation, making them some of the most hostile planets in the known galaxy. ✨
#pulsars⚡#exoplanets⚡#neutronstars
👉subscribe Universe Mysteries
🪐 In 2016, astronomers using the Hubble Space Telescope observed the exoplanet WASP-121b, where temperatures in its stratosphere soar above 2,500°C and molecules such as water vapor exist as glowing, superheated gas. The planet’s intense gravity causes it to stretch into a teardrop shape, while metals like iron and magnesium escape its atmosphere, streaming into space in a shimmering trail. ✨
#exoplanets⚡#atmosphere⚡#extremes
👉subscribe Universe Mysteries
🪐 Exoplanet 2MASS J2126–8140 holds the record for the widest known orbit around its star—about 1 trillion kilometers away, or nearly 7,000 times the distance from Earth to the Sun. This gas giant drifts so far from its host that a single "year" there lasts nearly 900,000 Earth years, exposing it to the coldest, loneliest planetary conditions ever measured. ✨
#exoplanets⚡#extremes⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2023, scientists used the James Webb Space Telescope to study the atmosphere of the exoplanet K2-18b, located about 120 light-years away in the constellation Leo, and detected molecules like methane and carbon dioxide in its thick atmosphere. While this doesn't prove the existence of aliens, these chemicals are considered potential signs that could support life as we know it, making K2-18b one of the most intriguing worlds in the ongoing search for extraterrestrial life. ✨
#aliens⚡#exoplanets⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Some of the loneliest travelers in the galaxy are rogue planets, which drift through space without orbiting any star. Astronomers have detected dozens of these starless worlds, like the giant PSO J318.5-22, floating about 80 light-years from Earth and glowing faintly in infrared as they slowly cool in the darkness. Rogue planets can form the same way as regular planets or be kicked out of their solar systems by gravitational encounters, making them true cosmic wanderers. ✨
#rogueplanets⚡#exoplanets⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos
👉subscribe Universe Mysteries
👉more Channels
🪐 Astronomers have identified the super-Earth exoplanet HD 40307g, located about 42 light-years away in the constellation Pictor, as a promising candidate for life because it may orbit within its star’s habitable zone—the region where temperatures could allow liquid water on the surface. With a mass at least seven times that of Earth and the right distance from its parent star, HD 40307g offers a real-world example of a potentially life-friendly world beyond our solar system. ✨
#exoplanets⚡#habitable⚡#universe⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The star WD 1856+534, located about 80 light-years away in the constellation Draco, is an unusually cool and faint white dwarf orbited by a giant planet-sized object at incredibly close range. This is remarkable because white dwarfs are dense, burned-out remnants of stars like our Sun, and scientists believe any planet this close should have been destroyed during the star’s previous red giant phase—making this system an exceptional survivor among stars. ✨
#stars⚡#white_dwarfs⚡#exoplanets⚡#nasa⚡#galaxy⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2020, researchers using the LOFAR radio telescope detected strange bursts of low-frequency radio waves coming from the red dwarf star GJ 1151, about 26 light-years from Earth. These signals are thought to be created by interactions between the star and an orbiting planet, and while not proof of aliens, such emissions spark excitement because similar interactions could reveal planets that might host life. ✨
#aliens⚡#exoplanets⚡#radio⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The exoplanet LTT 9779b, discovered about 260 light-years away in the constellation Sculptor, is known as an "ultra-hot Neptune" because it orbits its star so closely that its dayside temperature climbs above 1,700°C—hot enough to vaporize metals. Despite these extreme conditions, observations with the Hubble and Spitzer telescopes have revealed a reflective, metallic atmosphere loaded with silicate (rock-forming mineral) clouds, making this planet a shimmering furnace world unlike any found in our solar system. ✨
#exoplanets⚡#extremes⚡#neptune⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries