Можно ли в Python создавать бинарные файлы? Конечно можно.
Для этого в Python есть следующие инструменты:
▫️ тип данных bytes и bytearray
▫️ открытие файла в режиме wb (write binary) или rb (read binary)
▫️ модуль struct
Про модуль struct поговорим в первую очередь.
Файл в формате JSON или Yaml внутри себя содержит разметку данных. Всегда можно определить где список начался а где закончился. Где записана строка а где словарь. То есть формат записи данных содержит в себе элементы разметки данных.
В binary-файле данные не имеют визуальной разметки. Это просто байты, записанные один за другим. Правила записи и чтения находятся вне файла.
Модуль struct как раз и помогает с организацией данных в таком файле с помощью определения форматов записи для разных частей файла.
Модуль struct преобразует Python-объекты в массив байт, готовый к записи в файл и имеющий определённый вид.
Для этого всегда следует указывать формат преобразования (или, как оно здесь называется - запаковки).
Формат нужен для того, чтобы выделить достаточное количество байт для записи конкретного типа объекта. В последствии с помощью того же формата будет производиться чтение.
При этом следует помнить что мы говорим о типах языка С а не Python.
Именно формат определяет, что записано в конкретном месте файла, число, строка или что-то еще.
Вот какие токены формата у нас есть.
Помимо этого, первым символом можно указать порядок байтов. На разных системах одни и те же типы данных могут записываться по-разному, поэтому желательно указать конкретный способ из доступных. Если этого не сделать, то используется символ '@', то есть нативный для текущей системы.
В строке формата мы пишем в каком порядке и какие типы собираемся преобразовать в байты.
Запакуем в байты простое число, токен "i".
>>> import struct
>>> struct.pack('=i', 10)
b'\n\x00\x00\x00'
Теперь несколько float, при этом нужно передавать элементы не массивом а последовательностью аргументов.
>>> struct.pack('=fff', 1.0, 2.5, 4.1)
b'\x00\x00\x80?\x00\x00 @33\x83@'
Вместо нескольких токенов можно просто указать нужное количество элементов перед одним токеном, результат будет тот же.
>>> struct.pack('=3f', 1.0, 2.5, 4.1)
b'\x00\x00\x80?\x00\x00 @33\x83@'
Теперь запакуем разные типы
>>> data = struct.pack('=fiQ', 1.0, 4, 100500)
я запаковал типы float, int и unsigned long long (очень большой int, на 8 байт)
b'\x00\x00\x80?\x04\x00\x00...'
Распаковка происходит аналогично, но нужно указать тот же формат, который использовался при запаковке. Результат возвращается всегда в виде кортежа.
>>> struct.unpack('=fiQ', data)
(1.0, 4, 100500)
Как видите, ничего страшного!
#lib#basic
NOX Energy Secures $1M Funding
NOX Energy has successfully raised $1 million in funding, with the round scheduled for December 18, 2024. For more details, visit NOX Energy.
#NOXEnergy#Funding#Investment#RenewableEnergy
Turning Renewables into Reusables — Green University Partners with EURECA
✅Green University met with the representative of the EURECA – Renewable Energy in Central Asia project to discuss cooperation in circular economy, waste management, and renewable energy recycling.
🔵During the meeting, Ms. Bettina Löwentraut-Duran, Energy Advisor at the GIZ Office in Uzbekistan and expert under the EURECA project, proposed establishing a Knowledge Hub at Green University — a platform to connect academia, industry, and international partners for sustainable solutions.
✅Both sides expressed interest in promoting innovation, research, and green transformation in Uzbekistan and across Central Asia.
#EURECA#Sustainability#CircularEconomy#RenewableEnergy
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
🌞🇿🇦 South Africa’s Solar Breakthrough
In 2005, Prof. Vivian Alberts (pictured) of the University of Johannesburg developed a groundbreaking thin-film solar technology that could transform renewable energy.
Instead of thick, costly silicon panels, his design uses a metal-based semiconductor alloy only 3 microns thick (vs. ~300 microns for standard silicon panels) — dramatically reducing material costs.
Through his company PTiP (Photovoltaic Technology Intellectual Property), and in partnership with German engineering firm Singulus Technologies, a semi-commercial facility was launched in Stellenbosch to produce these next-gen panels.
🔋Why it matters:
⚡️ Far cheaper to manufacture
🌥 Generates power even in cloudy weather
🌍 A major step toward clean, affordable energy
#SouthAfrica#Innovation#Solar#RenewableEnergy#CleanEnergy#Sustainability
“Yangi Oʻzbekiston” universiteti va Xitoy xalq respublikasining nufuzli oliygohlari oʻrtasida hamkorlik aloqalari kengaymoqda
🌐 Bugun O‘zbekiston Respublikasi va Xitoy Xalq Respublikasi Ikkinchi ta’lim forumi boʻlib oʻtdi. Tadbir doirasida “Yangi Oʻzbekiston” universiteti Xitoyning bir qancha oliygohlari bilan aloqalarni yanada mustahkamladi.
Jumladan, dunyo reytingida 201–250 oʻrinda turuvchi Xi’an Jiaotong universiteti bilan anglashinuv memorandumi imzolandi.
✅ Kelishuvga koʻra qoʻshma ta’lim dasturlarini tashkil qilish, professor-oʻqituvchilar almashinuvini amalga oshirish va hamkorlikda laboratoriya xonalarini ochish kabi yoʻnalishlarda hamkorlik olib boriladi.
💡 “Yangi O‘zbekiston” universiteti — bu bilim, ijod va xalqaro hamkorlik uyg‘unlashgan muhit. Ilmiy g‘oyangizni hayotga tatbiq etish uchun eng yaxshi joy shu yerda!
🔁English
➖➖➖➖➖➖➖➖➖➖
#memorandum#Xitoy
#LetsDoResearchForNewUU#Engineering#Biotech#RenewableEnergy
⬇️Biz ijtimoiy tarmoqlarda:
Veb-sayt | Telegram | Instagram | Facebook
⚡ ETHIOPIA: AFRICA'S ENERGY POWERHOUSE
ኢትዮጵያ፡ የአፍሪካ የኃይል ማዕከል
Not just surviving - POWERING the future! 🌍💪
━━━━━━━━━━━━━━━━
⚡ GRAND ETHIOPIAN RENAISSANCE DAM (GERD)
ታላቁ የኢትዮጵያ ህዳሴ ግድብ
🏗️AFRICA'S LARGEST DAM:
• 74 BILLION m³ capacity
• 5,150 MW power
• 175m high (57 floors!)
• $5 billion - 100% Ethiopian-funded! 🇪🇹
• Status: OPERATIONAL ⚡
"የኢትዮጵያ ህዳሴ በኢትዮጵያውያን"
(Ethiopian Renaissance by Ethiopians)
━━━━━━━━━━━━━━━━
💡 WHAT IT MEANS
✅ Powers all Ethiopia + exports
✅ Sudan: flood control + steady flow
✅ Egypt: regulated water supply
✅ 100% renewable - ZERO emissions
✅ Lights millions of homes across East Africa
"One dam lighting half of Africa"⚡🌍
━━━━━━━━━━━━━━━
🌱 100% GREEN ENERGY NATION
Ethiopia's mix:
• Hydropower: 95%+
• Wind: Growing fast
• Solar: Huge potential
• Coal & gas: ZERO ✅
World's cleanest energy grid!🌿
━━━━━━━━━━━━━━━
🔌 ENERGY EXPORT - "AFRICA'S BATTERY"
Currently powering:
• 🇸🇩 Sudan: 100+ MW
• 🇩🇯 Djibouti: 60+ MW
• 🇰🇪 Kenya: Ready!
Future: South Sudan, Somalia, Eritrea, Egypt
💰 Billions in export income + regional peace
"የኢትዮጵያ ኃይል የአፍሪካን ያበራል"
(Ethiopian power lights Africa)
━━━━━━━━━━━━━━━
👷 OPPORTUNITIES FOR YOUTH
⚡CAREERS:
• የኤሌክትሪክ ምህንዲሶች (Engineers)
• Dam operators
• Renewable specialists
• Grid managers
🎓 Training at Ethiopian Electric Power, universities, GERD site
💼 Thousands of jobs, high salaries, build the future!
━━━━━━━━━━━━━━━
💚💛❤️ FUNDED BY ETHIOPIANS
Every citizen contributed:
• Salary donations
• Diaspora bonds
• Personal savings
More than infrastructure - это символ единства и гордости!
"ህዳሴ - የኢትዮጵያውያን ኩራት"
(Renaissance - Ethiopian Pride)
━━━━━━━━━━━━━━━
🌍 GLOBAL IMPACT
Ethiopia proves:
✅ Renewable energy works at scale
✅ Africa can self-fund development
✅ Green growth possible
✅ Cooperation beats conflict
The world watches - Ethiopia delivers!🌟
━━━━━━━━━━━━━━━
⚡ MORE COMING
🚀 Next projects:
• Koysha Dam (2,160 MW)
• Wind & solar expansion
• Geothermal (Rift Valley)
Ethiopia's energy future = UNLIMITED!💡
━━━━━━━━━━━━━━━
💡 MIND-BLOWING FACTS:
🤯 Reservoir takes 3 years to fill
🤯 Could power 300+ million people
🤯 12,000+ workers built it
🤯 10+ million m³ concrete
🤯 Already generating power!
━━━━━━━━━━━━━━━
⚡ FROM WATER TO POWER
🌊 Part 1: Water = Life source
⚡ Part 2: Power = Future engine
Ethiopian Renaissance by Ethiopians, for Africa!🇪🇹💪
The future is POWERED BY ETHIOPIA! 💡🌟
━━━━━━━━━━━━━━━
🌍 ETHIOPIA | ЭФИОПИЯ | ኢትዮጵያ
📱@ethiopia telegram
#GERD#EthiopiaEnergy#GreenEnergy#AfricaPower#EthiopianPride#RenewableEnergy#PoweringAfrica
Tesla's Bitcoin Commitment in Question Again
Over 60 public companies now hold #Bitcoin as a treasury reserve asset. Michael Saylor reminds Elon Musk of his promise regarding Tesla's acceptance of Bitcoin, noting that Bitcoin's mining is now over 56% powered by renewable energy. Tesla paused accepting Bitcoin payments in May 2021 due to concerns over mining's carbon footprint.
#Bitcoin#Tesla#Crypto#ElonMusk#Mining#RenewableEnergy#PublicCompanies#Treasury#CarbonFootprint#Saylor
🚀 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