Один из самых удобных способов записать данные это использование готовых форматов, такие как 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 phenomenon of synesthesia allows some people to experience a blending of senses—like seeing colors when hearing music or tasting flavors from words. This rare trait reveals how flexible and interconnected the human brain’s sensory pathways can be. ✨
#neuroscience⚡#consciousness⚡#perception
👉subscribe Interesting Planet
🌎 Marathon runners often report “time expansion,” where minutes can feel much longer during intense effort. This phenomenon is linked to changes in dopamine levels in the brain, affecting how we sense passing seconds. Scientists have tracked measurable shifts in perceived time during both high physical exertion and tasks demanding intense attention. ✨
#time⚡#neuroscience⚡#perception
👉subscribe Interesting Planet
👉more Channels
🌎 Time can seem to slow down or speed up based on emotional state. Studies show heightened fear, such as during accidents, leads people to recall more detail, but does not actually slow objective time. Experiments reveal our brain may stretch memory to make intense events feel longer, a phenomenon called time dilation. ✨
#neuroscience⚡#perception⚡#psychology
👉subscribe Interesting Planet
👉more Channels
🌎 The phenomenon of "temporal binding" describes how the brain knits together events that happen closely in time, making them feel like a single, unified event. Studies show people often judge actions and their effects as happening closer together than they really are, revealing how the human mind shapes our perception of time’s flow. ✨
#neuroscience⚡#psychology⚡#perception
👉subscribe Interesting Planet
👉more Channels
🌎 Time perception can be dramatically altered by body temperature, with research showing people exposed to cold environments often overestimate how much time has passed. This effect is linked to changes in the brain’s internal clock, and studies found that participants in cold water estimated intervals were about 20% longer than in neutral conditions. ✨
#neuroscience⚡#psychology⚡#perception
👉subscribe Interesting Planet
👉more Channels
🌎 Time can feel stretchy in our minds! In moments of stress or fear, your brain’s perception of time slows down—an effect called “time dilation.” The brain records more details during intense experiences, making events seem to last longer in memory. That’s why scary or thrilling moments feel like they stretch on forever, even though the real clock keeps ticking at its usual pace. ✨
#neuroscience⚡#psychology⚡#perception
👉subscribe Interesting Planet
🌎 Your sense of time can shift dramatically—scientists call these “time anomalies.” Strong emotions or new environments can make minutes feel like hours, or hours like seconds. This happens because your brain judges time based on how much information it’s processing, not by the clock. Moments packed with novelty or excitement seem longer, while routine days fly by unnoticed. ✨
#psychology⚡#perception⚡#brain
👉subscribe Interesting Planet
🌎 The phenomenon known as synesthesia causes some people to involuntarily link senses, such as perceiving numbers or letters as specific colors. Brain scans show increased cross-activity between sensory regions in synesthetes, and the trait is estimated to occur in about 4% of people. ✨
#neuroscience⚡#perception⚡#senses
👉subscribe Interesting Planet
👉more Channels
🌎 Our sense of time is shaped by specialized brain regions, including the cerebellum, basal ganglia, and the right supplementary motor area. Research using brain imaging and patient studies shows damage to these areas can create time perception anomalies—such as feeling time stretch, shrink, or fragment unexpectedly. The cerebellum, once thought only to control movement, plays a key role in accurately judging short time intervals. ✨
#neuroscience⚡#perception⚡#anomalies
👉subscribe Interesting Planet
👉more Channels
🌎 In rare cases, time perception can be distorted by neurological conditions such as temporal lobe epilepsy or brain injuries. People may report "time slowing down," déjà vu, or missing chunks of experience. Some individuals with temporal lobe seizures even describe feeling like time has stopped completely. ✨
#neuroscience⚡#perception⚡#anomalies
👉subscribe Interesting Planet
🌎 Your brain uses a region called the "suprachiasmatic nucleus" as its master clock, syncing your sense of time to light and dark cycles. Disruptions—like jet lag or shift work—can make time feel faster or slower, and this clock influences sleep, alertness, and body temperature rhythms. ✨
#perception⚡#neuroscience⚡#circadian
👉subscribe Interesting Planet
👉more Channels
🌎 Certain types of migraine can cause "time dilation" or "time compression"—making minutes feel like hours or vice versa. Research links these time perception anomalies to abnormal brain activity in areas responsible for processing time and sensory input. Migraine auras affecting time sense have been documented in up to 15% of patients. ✨
#migraine⚡#neuroscience⚡#perception
👉subscribe Interesting Planet
👉more Channels