Один из самых удобных способов записать данные это использование готовых форматов, такие как 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
🚗✨ Exciting News! The new Bentley Flying Spur is set to debut on September 10th! 🎉
This stunning sedan will feature the same V8 hybrid powertrain as the recently launched Continental GT. According to Bentley, it will be the "most powerful, dynamic, and economical four-door car in Bentley's 105-year history." 💪🌍
Stay tuned for more updates!
#BentleyFlyingSpur#LuxuryCars#HybridPower#Bentley#Auto
🚗✨ Exciting news! The updated Volvo XC90 is set to be unveiled on September 4th! 🌟
🔋 This refreshed model will feature a hybrid powertrain, ensuring it remains relevant until the brand transitions fully to electric vehicles by the end of the decade. ⚡️
Stay tuned for more updates!
#VolvoXC90#HybridPower#SustainableDriving#CarLaunch#Auto
🚗Introducing the upcoming McLaren P18!
🔥 Exciting news - this flagship supercar is set to be a 1000-horsepower all-wheel-drive hybrid! Only 399 lucky owners will get their hands on this beauty. 😍 Stay tuned for more details as clients have only seen a scale model of the design so far.
#McLarenP18#Supercar#HybridPower#AllWheelDrive#Auto🏁🔋🌟
🚗✨ Exciting news from McLaren! On October 6th, we might witness the unveiling of a brand new model that continues the legendary "1" lineage! 🌟
In a teaser video featuring the iconic F1 and P1, the date at the end hints at a thrilling reveal. 🔥
This hybrid supercar is set to deliver around 1000 hp, powered by a stunning V8 engine. 💪💨
Get ready for the next chapter in automotive excellence!
#McLaren#Supercar#HybridPower#ComingSoon#October6#Auto
🚗✨Introducing the Updated Audi A3 Hatchback: A Powerful Hybrid!✨🚗
⚙️ The heart of this beauty is the new 1.5 TFSI evo2 engine, replacing the previous 1.4-liter four-cylinder. With an increased compression ratio and higher fuel injection pressure, it's ready to impress! 💥
🔋 Coupled with a 116-hp electric motor, the 40 TFSI e variant produces a total of 204 hp and 350 Nm of torque, accelerating from 0 to 100 km/h in just 7.4 seconds! 🚀 Max speed? A thrilling 225 km/h! 🌟
🔥 For those craving more power, the 45 TFSI e variant boasts 272 hp and 400 Nm, hitting 100 km/h in just 6.3 seconds and a top speed of 237 km/h! 🏁💨
🛒 Orders are now open starting at €44,200!
#AudiA3#HybridPower#Innovation#LuxuryCars#CarEnthusiast#Performance#AudiLife#Auto🌍💚
🚗✨ Exciting News for BMW Fans!
The new BMW 5 Series Touring is here with electrified powertrains! ⚡️
Starting off, the lineup features a mild-hybrid 2.0L diesel engine. Now, it’s joined by a petrol alternative: a 2.0L engine paired with a 48V starter-generator, delivering 208 hp and 330 Nm. 🔥
Introducing the BMW 550e Touring: a full hybrid powerhouse with a 6-cylinder engine and an integrated electric motor in the 8-speed transmission, boasting an impressive 489 hp! 💪 On electric power alone, it can travel up to 90 km, reaching 0-100 km/h in just 4.4 seconds! ⏱️
And don’t miss the BMW i5 xDrive40 Touring! This all-electric beauty packs dual motors that deliver a total of 394 hp and 590 Nm. ⚡️🌍
#BMW#5Series#ElectricDriving#HybridPower#CarEnthusiast#LuxuryCars#Innovation#Sports🚘💚
🚗✨Introducing the BMW M5 Touring with M Performance Parts!🏁
BMW has unveiled stunning images of the new M5 Touring, now available with exclusive M Performance Parts! 🎉
This five-door beauty can be equipped with new aerodynamic body enhancements and a stylish alternative set of floor mats for the interior. Plus, an expanded range of accessories is now at your fingertips! 🛠️💎
Under the hood, the M5 Touring boasts a powerful hybrid powertrain delivering an impressive 727 hp and 1000 Nm of torque, allowing it to sprint from 0 to 100 km/h in just 3.6 seconds! ⚡️🚀 For those seeking even more thrill, the speed limiter can be raised to an exhilarating 305 km/h for an additional fee! 🏎️💨
#BMW#M5Touring#MPerformance#HybridPower#LuxuryCars#CarEnthusiasts#PerformanceParts#FastCars#Auto🚘🔥