Один из самых удобных способов записать данные это использование готовых форматов, такие как 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
🚀 Introducing the ultimate beast on wheels - Xiaomi's SU7 Ultra! With a whopping 1548 horsepower from its three electric motors, this sedan accelerates from 0 to 100 km/h in just 1.97 seconds and hits 200 km/h in 5.96 seconds. It boasts a top speed exceeding 350 km/h! 🏎️
#Xiaomi#SU7Ultra#SpeedDemon#ElectricPower#NurburgringRecordBreaker🏁🔥
🚗✨ Get Ready for the Modern Audi Sport Quattro! ✨🚗
On August 16th, the highly anticipated modern replica of the iconic Audi Sport Quattro will be unveiled live! 🎉🔥
Announced three years ago, this stunning electric powerhouse from German startup E-Legend boasts an impressive 816 horsepower!⚡💪 With only 30 units planned for production, this exclusive ride is set to turn heads! 😍
#AudiSportQuattro#ELegend#ElectricPower#CarEnthusiast#Supercar#ComingSoon#Auto
🚗💨 Exciting news from Lamborghini! The upcoming Lamborghini Temerario is set to unleash over 1000 horsepower! 🔥
Ruwen Mor, a former Audi engineer now at Lamborghini, revealed that the power of the V8 engine could increase from 200 to around 220 hp per liter. Plus, the car will feature three electric motors for an extra boost! ⚡️
The Temerario follows in the footsteps of the iconic Huracan, which had a naturally aspirated V10 engine with a peak output of 640 hp. While a V6 could have delivered even more power, the decision was made to stick with a higher cylinder count to meet customer expectations. 💪
#Lamborghini#Temerario#Supercar#1000HP#V8#ElectricPower#CarEnthusiast#LuxuryCars#Auto
🚗✨ Introducing the all-new Bentley Flying Spur! ✨🚗
The fourth generation of this iconic sedan has arrived, and it’s not just a pretty face. With a stunning Ultra Performance Hybrid powertrain, it’s now the most powerful four-door Bentley in history! 💪🔋
🔧Power Specs:
- 4.0L Twin-Turbo V8 + Electric Motor
- 782 hp & 1000 Nm of torque 💥
- 0 to 100 km/h in just 3.5 seconds⏱️
- Up to 76 km on electric power alone! ⚡
#Bentley#FlyingSpur#LuxuryCars#HybridPerformance#CarEnthusiast#Innovation#LuxuryLifestyle#ElectricPower#Auto
🚀 France Shifts Focus to Electric Power Amid Rising Oil Prices
French Prime Minister Sebastien Lecornu announced a strategic shift in government policy, emphasizing investment in electric power over short-term fuel aid. Bloomberg posted on X that this decision comes in response to the recent surge in oil prices triggered by the conflict in Iran. Lecornu highlighted the importance of supporting households and businesses in transitioning to electric power as a sustainable solution to the energy crisis. The government aims to reduce dependency on fossil fuels and promote cleaner energy alternatives. This move is part of a broader effort to address the economic impact of rising oil prices and ensure long-term energy security for the nation.
#France#ElectricPower#OilPrices#EnergyTransition#RenewableEnergy#EnergyPolicy#SustainableEnergy#FossilFuelReduction#EnergySecurity#EconomicImpact
Bitwise Launching Bitcoin Standards ETF
Bitwise is set to launch the Bitcoin Standard Company ETF, targeting companies with substantial Bitcoin holdings. Criteria include: holding at least 1,000 Bitcoins, market cap over $100 million, daily liquidity of $1 million+, and a public float of at least 10%. Read more
In Ethiopia, Bitcoin mining fueled by the Grand Renaissance Dam contributes 18% of the Ethiopian Electric Power Company's revenue. Recent investments in mining have topped $1 billion, with the government partnering with 25 companies to leverage low electricity costs of about 3.2 cents/kWh. Read more
#Bitcoin#ETF#Mining#Ethiopia#Electricity#Crypto#Investment#GerD#Revenue#Bitwise#Blockchain#Finance#CorporateReserves#Energy#MarketValue#Liquidity#PublicFloat#Africa#Partnership#InternationalMiners#ElectricPower