TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #241 · 5 мај

Можно ли в 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

Hashtags

Резултати

Пронајдени 15 слични објави

Пребарај: #remember

当前筛选 #remember清除筛选
Lsposed Modules Updates Tracker

@lsposed_Modules_Updates_Trackers · Post #6229 · 18.03.2026 г., 15:30

#Remember#rafareborn 模块:eu.hxreborn.remembermysort 简介:Remember My Sort 版本:300-3.0.0 更新时间:2026/03/18 18:13:22 更新日志: 💥 BREAKING CHANGES due to df21727 - migrate to libxposed API 101 (commit by @hxreborn): Migrates from libxposed API 100 to 101. API 100 will no longer be supported once 101 is officially released. An LSPosed Manager with API 101 support may not be @lsposed_Modules_Updates_Trackers | @lsposed_Geeks_Bot

Lsposed Modules Updates Tracker

@lsposed_Modules_Updates_Trackers · Post #6153 · 09.03.2026 г., 21:30

#Remember#rafareborn 模块:eu.hxreborn.remembermysort 简介:Remember My Sort 版本:202-2.0.1 更新时间:2026/03/10 04:51:04 更新日志: 🐛 Bug Fixes ef31320 - prevent dimId from being misinterpreted as the sort direction (commit by @hxreborn) Restores sort preferences for users upgrading from v1.x. @lsposed_Modules_Updates_Trackers | @lsposed_Geeks_Bot

Journey to Fluency

@fluencyinenglish · Post #7068 · 23.04.2019 г., 03:06

‍#grammar #remember #infinitive 1⃣ Remember + Infinitive 1⃣ به خاطر داشتن کاری که باید در اینده انجام دهید 2⃣ Remember + Gerund 2⃣ به خاطر داشتن کاری که در گذشته انجام داده‌اید 🆘 Infinitive: to + Verb 🆘 Gerund: Verb + ing @ieltsstrategies @fluencyinenglish

Journey to Fluency

@fluencyinenglish · Post #6746 · 08.01.2019 г., 06:20

#remember #forget #try @fluencyinenglish ❇️Remember + gerund This is when you remember something that has happened in the past. You have a memory of it, like being able to see a movie of it in your head. I remember going to the beach when I was a child. (= I have a memory of going to the beach). He remembers closing the door. (= He has a memory of closing the door). @fluencyinenglish ❇️Remember + to + infinitive This is when you think of something that you need to do. (And usually, you then do the thing). I remembered to buy milk. (= I was walking home and the idea that I needed milk came into my head, so I bought some). She remembered to send a card to her grandmother @fluencyinenglish ❇️ Forget + gerund This is the opposite of remember + gerund. It's when you forget about a memory, something that you've done in the past. Have we really studied this topic before? I forget reading about it. I told my brother that we'd spent Christmas at Granny's house in 1985, but he'd forgotten going there. @fluencyinenglish ❇️Forget + to + infinitive This is the opposite of remember + to + infinitive. It's when you want to do something, but you forget about it. I forgot to call my mother. (= I wanted to call my mother, but when it was a good time to call her, I forgot. I was thinking about something else, and the idea to call my mother didn't come into my head). She keeps forgetting to bring his book back. @fluencyinenglish ❇️Try + gerund This is when you do something as an experiment. The thing you do is not difficult, but you want to see if doing it will have the result that you want. I wanted to stop smoking, so I tried using nicotine patches. (= Using nicotine patches was easy, but I wanted to know if it would help me stop smoking). She tried giving up chocolate, but it didn't help her lose weight. (It was easy for her to give up chocolate. She gave it up to see if it would help her lose weight, but it didn't). @fluencyinenglish ❇️Try + to + infinitive This is when the thing you do itself is difficult. In the present tense or future tense, this means you might not succeed in doing it. In the past tense, it means that you made an effort to do the thing, but you did not succeed. I'll try to carry the suitcase, but it looks too heavy for me. She tried to catch the bus, but she couldn't run fast enough @fluencyinenglish ❇️Regret + gerund This is when you are sorry about something you did in the past and you wish you hadn't done it. I regret going to bed so late. I'm really tired today. She regrets leaving school when she was sixteen. She wishes that she had studied more and then gone to university. @fluencyinenglish ❇️Regret + to + infinitive We use this construction when we are giving someone bad news, in quite a formal way. The verb is almost always something like 'say' or 'tell' or 'inform'. I regret to tell you that the train has been delayed. The company regrets to inform employees that the London office will close next year. @fluencyinenglish

12
ПретходнаСтраница 1 од 2Следна