Один из самых удобных способов записать данные это использование готовых форматов, такие как 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 world's longest straight-line journey between two points using only latitude and longitude runs over 13,589 km from Liberia on Africa’s coast to eastern China, crossing no ocean. ✨
#coordinates⚡#distance⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🪐 The galaxy JADES-GS-z14-0, discovered in 2023 with the James Webb Space Telescope, is one of the farthest objects ever seen—its light has traveled for about 13.5 billion years to reach Earth. Observing JADES-GS-z14-0 lets astronomers look back to when the universe was less than 300 million years old, offering a rare glimpse into the early stages of galaxy formation just after the Big Bang. ✨
#galaxies⚡#distance⚡#universe⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The James Webb Space Telescope has spotted galaxy JD1 (also known as MACS0647-JD1), whose light began its journey over 13.3 billion years ago—when the universe was only about 4% of its current age. Observing JD1 allows scientists to study what galaxies looked like close to the cosmic dawn, revealing the structure of the universe in its earliest moments. ✨
#galaxies⚡#distance⚡#universe⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The galaxy CEERS-93316, discovered by the James Webb Space Telescope, is one of the most distant galaxies ever observed—its light began traveling toward us more than 13.4 billion years ago. Seeing CEERS-93316 means we are looking back in time to when the universe was less than 300 million years old, just a tiny fraction of its current age, revealing the earliest stages of galaxy formation after the Big Bang. ✨
#galaxies⚡#distance⚡#universe⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The galaxy named Earendel’s host, WHL0137-LS, contains the most distant single star ever detected—a star nicknamed Earendel whose light has taken about 12.9 billion years to reach Earth. Thanks to a powerful gravitational lens (a natural "magnifying glass" formed by another galaxy cluster), the Hubble Space Telescope was able to spot Earendel, offering a rare view of a lone star shining when the universe was less than a billion years old. ✨
#universe⚡#distance⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The galaxy ZF-COSMOS-20115, located more than 12 billion light-years from Earth, surprised astronomers by being "dead"—no longer forming new stars—when the universe was just 1.7 billion years old. Studying such distant, quenched galaxies helps scientists understand how some of the earliest cosmic structures formed and evolved in the young universe, illuminating the extreme environments at the farthest reaches of space and time. ✨
#galaxies⚡#distance⚡#universe⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The galaxy Maisie’s Galaxy (CEERS-93316), discovered by the James Webb Space Telescope, is one of the most distant objects ever observed, with its light traveling for about 13.4 billion years to reach Earth. We're seeing Maisie’s Galaxy as it existed just a few hundred million years after the Big Bang, providing a rare glimpse into the universe's earliest moments when the first galaxies were assembling and stars began to shine. ✨
#universe⚡#distance⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🌍 The world’s longest scheduled nonstop passenger flight connects New York and Singapore, covering about 15,300 kilometers in nearly 19 hours—highlighting advances in global air transport geography. ✨
#aviation⚡#distance⚡#networks⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🪐 The galaxy HD1, discovered in 2022, may be the most distant known object in the universe—its light has traveled more than 13.5 billion years to reach us. Observing HD1 gives astronomers a rare window into the universe just 300 million years after the Big Bang, offering clues to how the earliest galaxies and stars began to form in the cosmic dawn. ✨
#galaxies⚡#distance⚡#earlyuniverse⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The James Webb Space Telescope has observed the galaxy JADES-GS-z7-01-QU, one of the most distant “quiescent” galaxies ever found, meaning it has stopped making new stars even though its light began traveling to us over 13 billion years ago. Seeing JADES-GS-z7-01-QU lets scientists study how some galaxies aged and shut down astonishingly early, offering a rare glimpse into the universe’s remote past when cosmic structures were just beginning to take shape. ✨
#galaxies⚡#distance⚡#telescopes⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels