Один из самых удобных способов записать данные это использование готовых форматов, такие как 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
🪐 Near the center of the Small Magellanic Cloud, scientists have discovered a magnetar called SXP 1062 with a magnetic field so strong it can reshape atoms and trigger intense X-ray outbursts. Magnetars are a rare kind of neutron star—ultra-dense remnants of exploded massive stars—whose magnetic fields are trillions of times stronger than Earth's and can even change the properties of empty space around them, making these cosmic magnets among the universe's most extreme phenomena. ✨
#magnetars⚡#neutronstars⚡#spacefacts⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The star VY Canis Majoris, located about 3,900 light-years from Earth, is one of the largest known stars in the universe—so huge that if placed at the center of our solar system, its surface would reach beyond the orbit of Jupiter. This red hypergiant loses mass at an incredible rate, creating vast clouds of dust and gas that make it appear as a dim, shifting patch in telescopes rather than a sharp point of light. ✨
#unusualstars⚡#hypergiants⚡#spacefacts⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the spiral galaxy Messier 81, astronomers use precise observations of variable stars called Cepheids to confirm that light travels at a constant speed—299,792 kilometers per second—across millions of light-years. By timing the changes in these stars' brightness, scientists can measure vast intergalactic distances, showing that the universal speed limit of light holds true even when crossing the immense gulf between galaxies. ✨
#speedoflight⚡#Messier81⚡#spacefacts⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
The Moon takes about 29.5 Earth days to go from one sunrise to the next. Daylight lasts around 14.75 days, and night also lasts about 14.75 days. This long day and night happen because the Moon spins slowly and moves around Earth at the same time. We always see the same side of the Moon because of this. 🌕🌑
[Read more]
@googlefactss#Moon#LunarDay#SpaceFacts#Astronomy
The 1967 Outer Space Treaty says no country can own the Moon, but rules about mining are still unclear. Working on the Moon could also be dangerous for human health.
The Moon has water ice and rare metals that could help future space missions. But mining the Moon will damage its surface and spread potentially harmful dust. 🌕🚀
[Read more]
#MoonMining#SpaceLaw#OuterSpaceTreaty#SpaceFacts@googlefactss
During Apollo 10, a piece of poop floated inside the spaceship. The astronauts al denied it was theirs. In zero gravity, everything floats. 🚀💩
@googlefactss
#Apollo10#SpaceFacts#ZeroGravity#Astronauts#SpaceHistory
Pluto is slightly bigger than Russia.
Pluto has a surface area of about 17.65 million km².
Russia has an area of about 17.1 million km².
Some sources say otherwise because of old measurements or rounding.
Those sources are wrong.
🪐🌍📏
[Source 1]
[Source 2]
@googlefactss
#Pluto#Russia#SpaceFacts#Geography#NASA#Science#planet#dwarfplanet