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

Резултати

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

Пребарај: #know

当前筛选 #know清除筛选
Business Lessons™

@business_idea4 · Post #4733 · 27.01.2026 г., 17:26

Here are 5 key takeaways from the book "STRATEGIZE TO WIN" - 1. #Know your strengths and weaknesses. This is the foundation of any successful strategy. Once you know what you're good at and what you're not so good at, you can start to build a strategy that plays to your strengths and minimizes your weaknesses. 2. #Set clear goals. What do you want to achieve? What are your long-term and short-term goals? Once you know what you want to achieve, you can start to develop a strategy to get there. 3. #Understand your competition. Who are your competitors? What are their strengths and weaknesses? What are their goals? Once you understand your competition, you can start to develop a strategy that will give you an edge. 4. #Be flexible. The world is constantly changing, so your strategy needs to be flexible enough to adapt to change. Be prepared to adjust your strategy as needed. 5. #Execute your strategy. This is the most important step of all. Once you have a strategy, you need to execute it. This means taking action and making sure that your strategy is working. Here are some additional key takeaways from the book: A. #Strategy is not a one-time event. It is an ongoing process that needs to be reviewed and updated regularly. B. #Strategy is not about perfection. It is about progress. You will never have a perfect strategy, but you can always improve your strategy by learning from your mistakes and by making adjustments as needed. C. #Strategy is about execution. It is not enough to have a good strategy. You also need to be able to execute your strategy effectively. I hope these key takeaways help you on your journey to strategizing to win. 💠Join 🔺 Share @Business_Idea4💠

MONEY SECRETS

@businessideas101 · Post #1247 · 14.06.2025 г., 06:23

Here are 5 key takeaways from the book "STRATEGIZE TO WIN" - 1. #Know your strengths and weaknesses. This is the foundation of any successful strategy. Once you know what you're good at and what you're not so good at, you can start to build a strategy that plays to your strengths and minimizes your weaknesses. 2. #Set clear goals. What do you want to achieve? What are your long-term and short-term goals? Once you know what you want to achieve, you can start to develop a strategy to get there. 3. #Understand your competition. Who are your competitors? What are their strengths and weaknesses? What are their goals? Once you understand your competition, you can start to develop a strategy that will give you an edge. 4. #Be flexible. The world is constantly changing, so your strategy needs to be flexible enough to adapt to change. Be prepared to adjust your strategy as needed. 5. #Execute your strategy. This is the most important step of all. Once you have a strategy, you need to execute it. This means taking action and making sure that your strategy is working. Here are some additional key takeaways from the book: A. #Strategy is not a one-time event. It is an ongoing process that needs to be reviewed and updated regularly. B. #Strategy is not about perfection. It is about progress. You will never have a perfect strategy, but you can always improve your strategy by learning from your mistakes and by making adjustments as needed. C. #Strategy is about execution. It is not enough to have a good strategy. You also need to be able to execute your strategy effectively. I hope these key takeaways help you on your journey to strategizing to win. Thank you for reading 📖

搜书神器 读书动态

@BookLogSFW · Post #91115 · 18.05.2026 г., 06:03

书名:crash course for the new gre 4th editio - princeton review 文件:英文 · MOBI · 2MB · 4万字 · 0R 统计:308热度 | 5下载 | 1点赞 | 0收藏 评级:0分 (0人) 💬 质量:5分 (0人) 标签:#answer#question#Quantity#one#choices#two#number#choice#get#passage#re#time#word#like#questions#sentence#know#problem#GRE#first#find 上传:👤Swof #预览#SFW#收藏书籍 📜我喜欢的书籍[1本]