Можно ли в 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
😄Service
➖➖➖➖➖➖
A service can be an organisation or company that provides something useful or helpful for people.
🔘The park service look after the green spaces.
🔜It can also be the thing that is useful or helpful.
🔘Sorry, we don't offer a delivery service.
🔜We also use service to talk about types of businesses – if a company does something rather than makes something, it is a service. We often use it here as an adjective.
🔘Accountants work in the service economy.
🔜We often talk about service as the length of time that someone works for a company.
🔘He retired after forty years of service to the company.
🔜So, service is all about helping, or being useful to people, companies and organisations. Hopefully this video has been of service to you!
#Service👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys
😄Service
➖➖➖➖➖➖
A service can be an organisation or company that provides something useful or helpful for people.
🔘The park service look after the green spaces.
🔜It can also be the thing that is useful or helpful.
🔘Sorry, we don't offer a delivery service.
🔜We also use service to talk about types of businesses – if a company does something rather than makes something, it is a service. We often use it here as an adjective.
🔘Accountants work in the service economy.
🔜We often talk about service as the length of time that someone works for a company.
🔘He retired after forty years of service to the company.
🔜So, service is all about helping, or being useful to people, companies and organisations. Hopefully this video has been of service to you!
#Service👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys
HeyGem — это AI-сервис для генерации суперреалистичных 3D-персонажей, которых невозможно отличить от живого человека.
Нейронка формирует внешность аватара, мимику, эмоции, голос и прочие человеческие атрибуты — и все это всего за пару минут.
Не верите? Тогда посмотрите это видео
OpenAI Community | #service
DN42 access
本服务为那些无法轻松访问自身网络的用户以及希望体验 dn42 但又不想承担维护自有网络成本的用户提供 dn42 连接
默认情况下,地址从/96地址块中分配,如果您希望租用独立的/96前缀或更大的地址空间,请按照联系方式联系我
所有公开的PoP均已屏蔽来自中国境内的 IP 地址。如果您确实需要dn42 access,请与我联系并提供合理的理由
该服务由AS4242423377提供
- - - - - - -
The service provides DN42 connectivity to members who cannot easily access their own networks, as well as to those who would like to explore DN42 without the overhead of maintaining their own network.
By default, addresses are allocated from a /96 block. If you wish to lease a dedicated /96 prefix or a larger address space, please contact me using the methods provided in the contact information.
All publicly accessible PoP are blocked for IPs originating from within China. DN42 access from within China is not publicly available. If you genuinely require access, please contact me and provide a valid justification.
Hosted by AS4242423377.
Policy
本服务需要花费时间和金钱才能运行,但为了您的利益,我们免费提供。使用本服务是一种特权,而非权利。您必须合理使用本服务,以确保其他用户也能继续享受同样的便利。任何滥用、误用或干扰服务或其他用户的行为都可能导致您的访问权限立即被暂停或终止。
滥用行为包括但不限于:
- 过度使用资源
- 黑客攻击、病毒、木马等,或任何其他可能损害服务或对服务及其用户造成风险的干扰行为
- 传播可能导致民事或刑事责任的不良内容
- - - - - - -
This service require real time and financial resources to operate, yet are provided free of charge for your benefit. Access to the services is a privilege, not a right. You must use the services responsibly and considerately to ensure that other users can continue to enjoy the same opportunities. Any misuse, abuse, or activities that disrupt the service or other users may result in immediate suspension or termination of access.
Abuse could include, but is not limited to:
- Excessive use of resources
- Hacking, viruses, trojans etc or any other disruption that could harm or create risk to the services or its users
- Distribution of objectional content that could create a civil or criminal liability
PoP
## Toronto, Canada
Prefix: fdb6:fc6a:e66c:724f:fad1:d2cf::/96
Zerotier: 4753cf475f65b0fb
## Los Angeles, USA
coming soon
#announcement#service
DN42 access
本服务为那些无法轻松访问自身网络的用户以及希望体验 dn42 但又不想承担维护自有网络成本的用户提供 dn42 连接
默认情况下,地址从/96地址块中分配,如果您希望租用独立的/96前缀或更大的地址空间,请按照联系方式联系我
所有公开的PoP均已屏蔽来自中国境内的 IP 地址。如果您确实需要dn42 access,请与我联系并提供合理的理由
该服务由AS4242423377提供
- - - - - - -
The service provides DN42 connectivity to members who cannot easily access their own networks, as well as to those who would like to explore DN42 without the overhead of maintaining their own network.
By default, addresses are allocated from a /96 block. If you wish to lease a dedicated /96 prefix or a larger address space, please contact me using the methods provided in the contact information.
All publicly accessible PoP are blocked for IPs originating from within China. DN42 access from within China is not publicly available. If you genuinely require access, please contact me and provide a valid justification.
Hosted by AS4242423377.
Policy
本服务需要花费时间和金钱才能运行,但为了您的利益,我们免费提供。使用本服务是一种特权,而非权利。您必须合理使用本服务,以确保其他用户也能继续享受同样的便利。任何滥用、误用或干扰服务或其他用户的行为都可能导致您的访问权限立即被暂停或终止。
滥用行为包括但不限于:
- 过度使用资源
- 黑客攻击、病毒、木马等,或任何其他可能损害服务或对服务及其用户造成风险的干扰行为
- 传播可能导致民事或刑事责任的不良内容
- - - - - - -
This service require real time and financial resources to operate, yet are provided free of charge for your benefit. Access to the services is a privilege, not a right. You must use the services responsibly and considerately to ensure that other users can continue to enjoy the same opportunities. Any misuse, abuse, or activities that disrupt the service or other users may result in immediate suspension or termination of access.
Abuse could include, but is not limited to:
- Excessive use of resources
- Hacking, viruses, trojans etc or any other disruption that could harm or create risk to the services or its users
- Distribution of objectional content that could create a civil or criminal liability
PoP
## Toronto, Canada
Prefix: fdb6:fc6a:e66c:724f:fad1:d2cf::/96
Zerotier: 4753cf475f65b0fb
## Los Angeles, USA
coming soon
#announcement#service
🇩🇪 2.000 écoliers manifestent à Berlin contre la loi sur le service militaire et la militarisation de l’Allemagne, rapporte le correspondant de TASS.
#service#écolier#manifestation
🍹 Вы точно хотели бы такое, но прямо не догадывались об этом. Я говорю о новом расширении для Google Chrome от вьетнамской студии Bliss Interactive. Благодаря этому плагину будут включаться субтитры на YouTube именно в тот момент, когда вы начинаете хрустеть чипсами, из-за чего не слышны звуки из видео.
Как вы догадываетесь, здесь не обошлось без модели машинного обучения, которую обучили на записях аж 178 часов жевания чипсов и прочих снеков. Можете установить расширение (на самом деле технически не важно, хрустите вы Lay's или другими чипсами).
#AI#App#Service#Fun | Not Boring Tech
@DeleteEventsBot
Qué puede hacer este bot?
Este bot elimina mensajes de eventos (también conocidos como mensajes de acción) en supergrupos.
Idioma: Inglés
(visto en @BotsGram_cu)
#delete, #service, #message, #spam, #helper, #group, #supergroup, #join, #left, #pinned