Один из самых удобных способов записать данные это использование готовых форматов, такие как 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 asteroid 99942 Apophis, discovered in 2004, is a near-Earth object about 340 meters wide that will make an extremely close pass by Earth in 2029—closer than some satellites! Though it once raised fears of an impact, precise tracking shows it will safely miss us, offering astronomers a rare chance to study such a large asteroid up close as it sweeps just 31,000 kilometers above our planet. ✨
#asteroids⚡#nearEarth⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The asteroid 2023 DZ2, discovered in February 2023, is about 40–70 meters wide and made headlines for zooming past Earth closer than the Moon in March of that year. Scientists closely tracked 2023 DZ2 because an object of this size could cause city-wide damage if it ever impacted our planet, making its flyby an important real-world test of our planetary defense systems. ✨
#asteroids⚡#nearEarth⚡#hazards⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In 2018, the asteroid 2018 GE3—a space rock about 50 meters wide, similar in size to the object that exploded over Tunguska in 1908—passed less than half the distance to the Moon from Earth. Discovered just one day before its closest approach, 2018 GE3 highlights the ongoing need to monitor the skies for medium-sized asteroids that can come very close to our planet with little warning. ✨
#asteroids⚡#nearEarth⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The asteroid 2023 BU, only a few meters wide, passed less than 3,600 kilometers above Earth's surface in January 2023—closer than many satellites. Despite its tiny size, this near-miss shows how small space rocks can come undetected until they're almost upon us, highlighting the importance of constant sky monitoring for even the smallest cosmic intruders. ✨
#asteroids⚡#nearEarth⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The asteroid (153814) 2001 WN5, roughly 1 kilometer across, will pass exceptionally close to Earth in 2028—only about 248,000 kilometers away, closer than the Moon. Because of its size and fast approach, 2001 WN5 is classified as a "potentially hazardous asteroid," meaning it could cause regional devastation if it ever struck our planet, so astronomers track its orbit with special care. ✨
#asteroids⚡#nearEarth⚡#hazard⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The asteroid (99942) 2004 MN4, known as Apophis’s “cousin,” (163899) 2003 SD220, is a mountain-sized space rock that approaches Earth’s orbit about every December. Measuring roughly 1.6 kilometers long, its close passes remind scientists how even asteroids with well-known orbits can periodically come within just a few million kilometers of our planet, earning it a spot on NASA's list of potentially hazardous objects. ✨
#asteroids⚡#hazard⚡#nearEarth⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Asteroid (4581) Asclepius, discovered in 1989, is a near-Earth object that passed just 700,000 kilometers from our planet—less than twice the distance to the Moon—shortly after its discovery. Its previous approach in 1989 would have caused a massive explosion if it had impacted, making Asclepius a stark reminder of how some dangerous asteroids can slip past unnoticed until they're already close. ✨
#asteroids⚡#nearearth⚡#impact⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The asteroid (85713) 1998 SS49 is a near-Earth object spanning about 1 kilometer across, and its orbit crosses Earth's path around the Sun. Classified as a potentially hazardous asteroid due to its size and the proximity of its flybys, 1998 SS49 is closely tracked by astronomers to ensure that any changes in its trajectory don’t make it a future threat to our planet. ✨
#asteroid⚡#hazards⚡#nearEarth⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Discovered in 2013, asteroid 2013 TX68 drew attention due to its unpredictable orbit, which allowed it to pass within a few million kilometers of Earth—close enough that its next flyby in 2046 will be closely watched. This space rock is roughly 30 meters wide, similar in size to the Chelyabinsk meteor, and while it's not currently on a collision course, its uncertain path highlights the challenges of tracking smaller, potentially hazardous asteroids. ✨
#asteroids⚡#nearearth⚡#planetarydefense⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Asteroid (4660) Nereus is a near-Earth object about 330 meters wide, famous for its frequent close approaches to our planet due to its elongated orbit around the Sun. While it poses no immediate danger, Nereus occasionally comes within just a few million kilometers of Earth, making it one of the more closely watched space rocks for future planetary defense planning. ✨
#asteroids⚡#nearearth⚡#planetarydefense⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 One of the largest objects in space that could threaten Earth is Asteroid (3122) Florence, a giant 4.5-kilometer-wide rock that passed safely at about 7 million kilometers in 2017—but it regularly returns every few decades. Florence's path is well-tracked, but its size means that, if its orbit ever shifted, it could cause catastrophic damage to Earth, making it a key object for ongoing monitoring by planetary defense networks. ✨
#asteroid⚡#nearEarth⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Asteroid (2023) JK, discovered in May 2023, is about 200 meters wide and passed within 730,000 kilometers of Earth—closer than twice the distance to the Moon. Its swift approach was detected less than a week before its closest pass, demonstrating how new near-Earth objects can still surprise astronomers and reminding us that even mid-sized space rocks can appear on short notice. ✨
#asteroids⚡#nearearth⚡#spacehazards⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels