Один из самых удобных способов записать данные это использование готовых форматов, такие как 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 Zone of Silence in northern Mexico baffles visitors—radios and compasses fail, and strange meteorites have fallen here. Scientists suspect unusual magnetic minerals and local geology disrupt signals, making this desert a hotspot for unexplained natural phenomena. ✨
#mystery⚡#geology⚡#magnetism
👉subscribe Interesting Planet
🌍 Earth has a layered structure: a thin crust, a solid mantle, a liquid outer core, and a solid inner core. The deep core’s movement creates the planet’s magnetic field, vital for life. ✨
#planet⚡#geology⚡#magnetism⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Earth’s outer core is made of liquid iron and nickel and creates the planet’s magnetic field. This powerful shield protects life by deflecting harmful cosmic and solar radiation. ✨
#planet⚡#geology⚡#magnetism⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Auroras can ripple like curtains or spiral in arcs because solar particles follow Earth's magnetic field lines. Their shifting shapes reveal invisible patterns high above our polar regions. ✨
#aurora⚡#atmosphere⚡#magnetism⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Auroras glow when charged particles from the Sun hit Earth's magnetic field, making gases like oxygen and nitrogen light up green, red, and even rare purple or blue in the night sky. ✨
#aurora⚡#magnetism⚡#atmosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌎 Hidden beneath Jupiter’s clouds, the planet’s metallic hydrogen layer creates an enormous magnetic field. This magnetic field is about 20,000 times stronger than Earth’s and traps intense radiation belts. ✨
#Jupiter⚡#planets⚡#magnetism
👉subscribe Interesting Planet
👉more Channels
🪐 Spanning more than 300 light-years, a vast radio structure known as the "Orion Spur Radio Arc" weaves through our segment of the Milky Way. Detected by the LOFAR radio telescope, this arc is composed of incredibly energetic electrons spiraling around magnetic fields, revealing a hidden backbone of cosmic magnetism threading through our stellar neighborhood. ✨
#MilkyWay⚡#magnetism⚡#radio
👉subscribe Universe Mysteries
🌎 The mysterious Whistler waves are very low-frequency radio signals generated by lightning. They travel along Earth's magnetic field lines and can be converted to eerie whooshing or whistling sounds when played back as audio. These signals were first recorded by radio operators during World War I. ✨
#lightning⚡#magnetism⚡#radio
👉subscribe Interesting Planet
🪐 In the constellation Lynx lives an unusual star known as HD 45166, which has an incredibly strong magnetic field—about 43,000 times greater than Earth’s. This rare "magnetized helium star" shrouds itself in a thick, fast-moving wind of gas, and its unique magnetic properties provide astronomers with a rare look at how intense magnetism can shape the life and appearance of stars. ✨
#unusualstars⚡#magnetism⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🌍 Earth’s core spins slightly faster than its surface, a phenomenon called “super-rotation.” This hidden motion helps maintain our magnetic field, vital for navigation and life. ✨
#planet⚡#core⚡#magnetism⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Earth's magnetic field acts like a protective shield, deflecting harmful solar wind and cosmic rays. This invisible force helps preserve our atmosphere and supports life on the planet. ✨
#magnetism⚡#protection⚡#atmosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🪐 In the constellation Monoceros, the star HD 45166 is an unusually magnetic massive star with a surface magnetic field nearly 43,000 times stronger than Earth's. This extreme magnetism shapes the flow of gas around the star, producing powerful outflows and making HD 45166 a rare laboratory for studying the effects of magnetism on stellar evolution. ✨
#stars⚡#magnetism⚡#Monoceros⚡#nasa⚡#galaxy⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries