Один из самых удобных способов записать данные это использование готовых форматов, такие как 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 invention of the safety elevator by Elisha Otis in 1852 made skyscrapers possible. His design featured a locking mechanism that stopped the elevator if the hoisting cable snapped. Otis demonstrated this life-saving device at the 1854 World’s Fair in New York, boosting public trust in elevators. ✨
#inventions⚡#history⚡#engineering
👉subscribe Interesting Planet
👉more Channels
🌎 X-rays were discovered accidentally in 1895 by German physicist Wilhelm Röntgen. While experimenting with cathode rays, he noticed an unknown radiation that could pass through solids and reveal images of bones. Today, X-rays are a key tool in medicine and industry worldwide. ✨
#inventions⚡#history⚡#physics
👉subscribe Interesting Planet
👉more Channels
🌎 The invention of the modern stethoscope in 1816 by French physician René Laennec transformed medical diagnosis. By rolling paper into a tube, Laennec could hear internal chest sounds clearly, improving detection of lung and heart conditions. The first stethoscopes were made of wood and about 25 centimeters long. ✨
#history⚡#medicine⚡#inventions
👉subscribe Interesting Planet
👉more Channels
🌎 In 1867, Swedish chemist Alfred Nobel invented dynamite by stabilizing volatile nitroglycerin with an absorbent clay called kieselguhr. This made blasting much safer for construction and mining. Nobel later used his dynamite fortune to establish the Nobel Prizes in 1895. ✨
#inventions⚡#chemistry⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 In 1903, the Wright brothers achieved the first powered, controlled, and sustained flight of an airplane at Kitty Hawk, North Carolina. Their aircraft, the Wright Flyer, flew for 12 seconds and covered 36 meters. ✨
#inventions⚡#aviation⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 The accidental invention of safety glass happened in 1903, when French chemist Édouard Bénédictus dropped a glass flask coated with plastic cellulose nitrate. Rather than shattering, the glass cracked but held together, inspiring shatter-resistant windshields. By 1927, safety glass became standard in automobile manufacturing. ✨
#inventions⚡#chemistry⚡#history
👉subscribe Interesting Planet
👉more Channels
The first vending machine was invented in the 1st century AD by Greek engineer Heron of Alexandria. It dispensed holy water when a coin was inserted—the weight tilted a lever, opening a valve to release water before the coin dropped. 💧⚖️
[Learn more]
@googlefactss
#History#Inventions#Engineering#AncientGreece
Professor Muhammed Uvaze ixtirolari Buyuk Britaniyada patentlashtirilgani haqida Hudud informatsion dasturida lavha tayyorlandi.
#hudud#patent#inventions
⬇️Biz ijtimoiy tarmoqlarda:
Veb-sayt | Telegram | Instagram | Facebook
🌎 The discovery of radioactivity in 1896 by Henri Becquerel revealed that uranium salts emit invisible energy. This led to the identification of new elements like polonium and radium by Marie and Pierre Curie. Their work contributed to the development of X-ray machines and atomic science. The Curies isolated just 1 gram of radium from 8 tons of ore. ✨
#radioactivity⚡#discovery⚡#inventions
👉subscribe Interesting Planet
🌀💦 South African Invention That Changed Pool Life
Did you know the automatic pool cleaner was invented in 🇿🇦 South Africa?
👨🔧 In 1974, hydraulics engineer Ferdinand Chauvier (pictured), who had moved from the Belgian Congo to South Africa, came up with a way to take the hassle out of pool cleaning.
The result? The legendary Kreepy Krauly — one of the very first automatic pool cleaners, designed and built in Springs, South Africa. 🌍✨
His invention made pools around the world easier to maintain — and became a proudly South African contribution to everyday comfort.
🏊♂️ From Johannesburg to Los Angeles, millions of pools have been cleaned thanks to Chauvier’s idea.
#Inventions#SouthAfrica#Innovation#KreepyKrauly#History#MadeInSA