Можно ли в 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
#DidYouKnow❓
Relying on the healing power of nature, Naturopathy stimulates the human body's ability to heal itself!
Test your knowledge about Naturopathy. Take the quick quiz today!
Visit: https://quiz.mygov.in/quiz/naturopathy-quiz/
📢 The Weekly Wrap – 16 May 2025
1) #DidYouKnow Today is Drug Victims Remembrance Day?
An annual observance to rally together on the harms and trauma of drug abuse.
Visit the “Museum of Us” exhibition from 16 to 18 May at Suntec City, 10am to 8pm, to get an insider perspective on the impact of drug abuse and offer support in the healing process.
🔗 Show your support at: go.gov.sg/rday2025.
2) The Together, for Better roadshows: Back in your ‘hood!
Our roadshows are back, and we’re making our way to Bukit Panjang and Hougang this weekend!
What’s in store for you:
✅ Interactive exhibits
💼 Professional advice on jobs and upskilling
🎁 Join quizzes and win prizes
🔗 More details: togetherforbetter.gov.sg/events-and-roadshows/
See you at Hillion Mall and Hougang Mall on 17 & 18 May, from 11am to 8pm!
Daily Questions and Answers
1. The ‘Roof’ of the world is referred to which place?
Answer: Pamir knot
2. What is the currency in Cambodia?
Answer: Riel
3. What is dew point?
Answer: The temperature at which dew begins to evaporate
4. How do you measure the speed of wind?
Answer: Anemometer
5. Name the river that is not crossed by any bridges.
Answer: Amazon
#DidYouKnow
One million Earths could fit inside the sun!
Via @askmenow
News headlines: read here
Try: Quiz MCQ
For Fun: Be Like Bro , sarcasticLOL
1. How many countries are present in Africa?
Answer: 54 countries
2. Which planet is closest to Planet Earth?
Answer: Venus
3. What erupts from a volcano?
Answer: Lava, steam, ash, pieces of rock, and gaseous sulfur compounds
4. What is the name of the strait that separates the north and south islands of New Zealand?
Answer: Cook strait
5. Which is the direction at which wind blows?
Answer: Leeward direction
#DidYouKnow
At over 2,000 kilometers long, The Great Barrier Reef is the largest living structure on Earth
Via @askmenow
Know more about:
1- Venezuela Oil Crisis
2. Rohingya Refugee Crisis
News headlines(29.01.2021): read here
Try: Quiz MCQ
For Fun:Be Like Bro , sarcasticLOL
Today's Questions and Answers
1. Which is the coldest continent in the world?
Answer: Antarctica
2. Which is the world’s smallest country?
Answer: Vatican City
3. Where is the Colloseum located?
Answer: Rome, Italy
4. Where is the Tower Bridge located?
Answer: London, UK
5. Where is the Leaning Tower of Pisa located?
Answer: Pisa, Italy
#DidYouKnow
There is enough DNA in the average person’s body to stretch from the sun to Pluto and back — 17 times.
Via @askmenow
Today's news headlines: read here
Try: Quiz MCQ
For Fun: Be Like Bro , sarcasticLOL
Today's Questions and Answers
1. Which is the largest waterfall in the world?
Answer: Victoria Falls
2. Which is the largest desert in the world?
Answer: Sahara Desert
3. What are the branches of a river called?
Answer: Tributaries
4. Which is the largest island in the world?
Answer: Greenland
5. What heats the water in a hot spring?
Answer: Magma
#DidYouKnow
In a glass of water when you pour a handful of salt, the level of water does down
Via @askmenow
Today's news headlines: read here
Try: Quiz MCQ
For Fun: Be Like Bro , sarcasticLOL
Today's Questions and Answers
1. Which is the tallest mountain in the world?
Answer: Mount Everest
2. Which is the latitude that runs through the centre of the Earth?
Answer: Equator
3. What are the names of the 5 oceans of the world?
Answer: Indian Ocean, Southern Ocean, Atlantic Ocean, Pacific Ocean, and Arctic Ocean
4. Which country has the highest population?
Answer: China
5. Which is the longest river in the world?
Answer: The Nile, Africa
#DidYouKnow
The Paris Agreement on climate change was signed by the largest number of countries ever in one day.
Via @askmenow
Today's news headlines: read here
For fun visit : Be Like Bro , sarcasticLOL
Try : Quiz MCQ
Daily Questions and Answers
1. Aurora Borealis are created in which layer of atmosphere?
Ans. Thermosphere
2. What is the instrument used to measure wind speed?
Ans. Anemometer
3. Eiffel Tower is six inches taller in summer due to-
Ans. Thermal Expansion
4. Eiffel Tower is taller in which season-
Ans. Summer Season
5. Who was the first person to win the Nobel prize in physics?
Ans. Wilhelm Conrad Röntgen (1901)
#DidYouKnow
The reason the ocean has waves and has tides that switch from high to low is that the gravitational pull from the moon and the sun keep changing.
Via @askmenow
Know more about:
1- Aurora Borealis vs Aurora Australis
Today's headlines: read here
For fun: Visit @sarcasticLOL & @updateee
Daily Questions and Answers
1. Sleeping under the tree at night time is dangerous because trees produce some gas, what is the gas?
Ans. Carbon Dioxide
2. Sound waves cannot travel in?
Ans. Space or Vacuum
3. What is the full form of NASA?
Ans. National Aeronautics and Space Administration
4. What is the atomic number of sodium?
Ans. 11
5. What are the three subatomic particles in an atom?
Ans. Eelectrons, protons and neutrons
#DidYouKnow
The decimal number system we use today was invented in India.
Via @askmenow
Latest news: Hong Kong internet provider admits blocking pro-democracy website
Have fun with @sarcasticLOL
Daily Questions and Answers
1. We live in which layer of atmosphere?
Ans. Troposphere
2. 1 Nanometer is equals to how many meters?
Ans. 10 power minus 9 meters
3. Sun appears red at morning and evening because of?
Ans. Scattering of light
4. Which Scientist named the words positive and negative in electrical charges?
Ans. Benjamin Franklin
5. A Reusable space rocket is called as?
Ans. Space shuttle
#DidYouKnow
Dogs have an amazing sense of hearing and can hear sounds at four times the distance than humans can.
Via @askmenow
Latest news:Yellow mealworms become first insect approved in EU as human food
Know more about:Mealworm