Можно ли в 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
🐈⬛Мы возвращаемся к вам с итогами третьей недели рубрики Q&A
🔢 Появились ли новые тенденции в исследованиях с появлением ИИ?
🔢 Может ли искусственный интеллект самостоятельно провести исследование?
🔢 Какие существуют этические нормы по использованию ИИ?
🐈⬛ На эти и другие ваши вопросы по теме «Влияние искусственного интеллекта на научную сферу журналистики и медиаисследований» ответила заведующая кафедрой цифровых медиакоммуникаций Камилла Ренатовна Нигматуллина
🐈⬛ Завтра мы вернемся с анонсом следующего гостя, а пока предлагаем вам ознакомиться с ответами эксперта
#QnA
❗️❗️❗️Dear subscribers,❗️❗️❗️ please join us for a livestream on Friday, 19 July, at 8pm GMT!
Our friend Alex at UkraineWarTruth
had his YouTube channel banned after he published the video he made in Mariupol
The banned channel was instrumental in the great work Alex has been doing since 2014, bringing the truth about the Donbass to the people in the West. It had hundreds of thousands of views and thousands of subscribers, and it was taken down without a warning after posting three new videos, which were first-hand eye-witness accounts and which didn't break a single YouTube rule.
Please join us in supporting Alex's work by watching his latest video and subscribing to his Telegram channel: https://t.me/Ukraine_War_Truth
❗️We'd also like to invite you to our upcoming livestream on Friday, 19 July, at 8pm GMT, where Alex will join #TheBelgorodBrit to speak about Mariupol, Belgorod, Russia, Ukraine... and the freedom of speech, of course!
Please post any questions or comments in this thread.
#QnA
#stream
📱InfoDefenseENGLISH
📱InfoDefense
❗️❗️❗️Dear subscribers,❗️❗️❗️ please join us for a livestream on Friday, 19 July, at 8pm GMT!
Our friend Alex at UkraineWarTruth
had his YouTube channel banned after he published the video he made in Mariupol
The banned channel was instrumental in the great work Alex has been doing since 2014, bringing the truth about the Donbass to the people in the West. It had hundreds of thousands of views and thousands of subscribers, and it was taken down without a warning after posting three new videos, which were first-hand eye-witness accounts and which didn't break a single YouTube rule.
Please join us in supporting Alex's work by watching his latest video and subscribing to his Telegram channel: https://t.me/Ukraine_War_Truth
❗️We'd also like to invite you to our upcoming livestream on Friday, 19 July, at 8pm GMT, where Alex will join #TheBelgorodBrit to speak about Mariupol, Belgorod, Russia, Ukraine... and the freedom of speech, of course!
Please post any questions or comments in this thread.
#QnA
#stream
📱InfoDefenseENGLISH
📱InfoDefense
Qatar News Agency
Kazakh Vice Minister of Culture, Sports: Close Relations Between #Kazakhstan and #Qatar, Large Cooperation Projects Await Both Sides.
Chairman of the Management Board of JSC National Company “Kazakh Tourism” to #QNA: After HH the Amir's visit, we hope to establish great cooperation between #Kazakhstan and #Qatar, especially in the field of tourism.
Daily Questions-Answers, Facts, Idioms, Riddles and Quotes
#QnA
1. The pollutants which move downward with percolating groundwater are called
Ans . Leachates
2. Hasdo Valley in Chhattisgarh is famous for
Ans . Coal mines
3. Special Theory of Relative was proposed in
Ans . 1905
Via @askmenow
--------------------------------
#DidYouKnow
Eiffel Tower is six inches taller in summer due to 'Thermal Expansion'
#Idiom
"A hot potato"
What it means?Check Answer
#Riddle
"Where does today come before yesterday'
What is it?Check Answer
#Quote
"Optimism is a happiness magnet. If you stay positive, good things and good people will be drawn to you."
~ Mary Lou Retton
-----------------------------
Partnership with:Be Like Bro, sarcasticLOL, News Clips, Word Coach, Quiz MCQ, Ask Me Idiom & Ask Me Riddle
Daily Questions-Answers, Facts, Idioms, Riddles and Quotes
#QnA
1. Celsius and Fahrenheit show the same temperature at
Ans . 40
2. Exchange particle in Quark-Quark Interaction
Ans . Gluon
3. The working of a rockets based on the principle of:
Ans . Conservation of momentum
Via @askmenow
--------------------------------
#DidYouKnow
There are ice caves in Iceland that have hot springs.
#Idiom
"Letting the cat out of the bag"
What it means?Check Answer
#Riddle
"What has words, but never speaks"
What is it?Check Answer
#Quote
"Two roads diverged in a wood and I took the one less traveled by, and that made all the difference."
~ Robert Frost
-----------------------------
Partnership with:Be Like Bro, sarcasticLOL, News Clips, Word Coach, Quiz MCQ, Ask Me Idiom & Ask Me Riddle
Daily Questions-Answers, Facts, Idioms, Riddles and Quotes
#QnA
1. In Computer, what is the full form of UPS?
Ans . UPS = Uninterruptable Power Supply
2. Which city is built on more than 100 islands?
Ans . Venice
3. Name of vegetable which is also known as a flower?
Ans . Broccoli
4. Highest electrical conductivity found in which element?
Ans . Silver
5. Thermometer made first by?
Ans . Gauss
Via @askmenow
--------------------------------
#DidYouKnow
Lions have been observed to rest for a major part of the day, usually around 20 hours.
#Idiom
"A blessing in disguise"
What it means?Check Answer
#Riddle
"What can you hold in your left hand but not in your right"
What is it?Check Answer
#Quote
"Circumstances are beyond the control of man, but his conduct is in his own power."~Benjamin Disraeli
-----------------------------
Partnership with:Be Like Bro, sarcasticLOL, News Clips, Word Coach, Ask Me Idiom & Ask Me Riddle
Daily Questions-Answers, Facts, Idioms, Riddles and Quotes
#QnA
1. White Revolution’ is related to what?
Ans . Milk Production
2. A very successful invention ‘Liquid Oxygen’ discovered by whom?
Ans . Dewar
3. What is the radiant energy of the sun is transmitted?
Ans . Short waves
4. What is the chemical formula of ‘Sodium Hydroxide’?
Ans . NAOH
5. The Folded Earth book was written by?
Ans . Anuradha Roy
6. Barometer was invented by?
Ans . F. Banting
7. Which rays is very helpful in Long distance photography?
Ans . Infra-Red rays
Via @askmenow
____________________
____________________
#DidYouKnow
Grasshoppers have ears in their bellies
#Idiom
"A bird in the hand is worth two in the bush"
What it means?Check Answer
#Riddle
I’m light as a feather, yet the strongest person can’t hold me for five minutes.
What am I?Check Answer
#Quote
"If you spend your whole life waiting for the storm, you'll never enjoy the sunshine." ~ Morris West