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 слични објави

Пребарај: #btogether

当前筛选 #btogether清除筛选
HDB

@SingaporeHDB · Post #3175 · 17.04.2026 г., 10:54

Take our quiz to test your HDB knowledge ⬇️ Are you ready to #BTOgether? Let’s see how much you know about buying a BTO flat! P.S. No stress, this is an open book quiz 😉 You can check out these BTO-related guides on MyNiceHome first: 💰CPF Housing Grants for HDB Flat Buyers 🔍HDB Flat Types and Classification 🏠How to Buy a BTO Flat

Hashtags

HDB

@SingaporeHDB · Post #2136 · 11.01.2024 г., 10:02

How will your 2024 look like? If you’re planning to apply for a BTO flat in 2024, you can look forward to 3 sales launches this year – with the first sales launch happening in February! Apply for your HFE letter by 15 January, if you’re thinking of to participating in the upcoming February sales launch. Get ready to #BTOgether🏠 Find out more at https://homes.hdb.gov.sg.

Hashtags

HDB

@SingaporeHDB · Post #2111 · 08.12.2023 г., 03:01

Planning to purchase a new home at the December sales launch? Check out which flats you can consider according to your monthly household income! Work out your housing budget with HDB’s online calculators at https://homes.hdb.gov.sg#BTOgether

Hashtags

HDB

@SingaporeHDB · Post #2099 · 07.12.2023 г., 10:09

Looking for a 4-room flat this sales launch? Here’s what the sums could look like. Head over to https://homes.hdb.gov.sg to find out more about the grants and schemes available for first-timer families, and use our financial calculators to plan your purchase. #BTOgether

Hashtags

HDB

@SingaporeHDB · Post #2088 · 07.12.2023 г., 03:31

Looking for a 3-room flat this sales launch? Here’s what the sums could look like. Head over to https://homes.hdb.gov.sg to find out more about the grants and schemes available for first-timer families, and use our financial calculators to plan your purchase. #BTOgether

Hashtags

HDB

@SingaporeHDB · Post #2081 · 06.12.2023 г., 02:00

Check out the prices of each flat type on offer this sales launch! Work out your housing budget with HDB’s online calculators at https://homes.hdb.gov.sg#BTOgether

Hashtags

HDB

@SingaporeHDB · Post #2072 · 05.12.2023 г., 07:20

JUST IN: 6,057 flats on offer at the December BTO sales launch! Find out more about the projects at Bedok, Bishan, Bukit Merah, Bukit Panjang, Jurong West, Queenstown, and Woodlands. About 50% of the BTO flats launched this sales launch have a wait time of 4 years or less – for those who are looking to move into their flats sooner, the flats at Sin Ming Residences have wait time of about 2 years and 8 months, while Jurong Arcadia has a wait time of about 3 years and 1 month. Get your HFE letter ready, and apply for your new home at https://homes.hdb.gov.sg by 11 December. #BTOgether

Hashtags

HDB

@SingaporeHDB · Post #2042 · 11.11.2023 г., 03:01

It’s 11/11 and we did not forget you 💖 In the second half of 2024, singles can apply for 2-room Flexi flats across all HDB projects islandwide, not just in non-mature estates! We will also launch up to 14,000 2-room Flexi BTO flats from 2024 to 2026 to meet demand. #BTOgether

Hashtags

HDB

@SingaporeHDB · Post #1929 · 24.09.2023 г., 04:01

Ready to #BTOgether at the upcoming sales launch? It’s as easy as 🔤! To plan your budget, use our online calculators at https://homes.hdb.gov.sg. Simply input the info from your approved HFE letter, and you will be able to work out your flat budget. More about the new First-Timer (Parents & Married Couples) category and priority schemes.

Hashtags

HDB

@SingaporeHDB · Post #1843 · 07.07.2023 г., 04:00

Swiftie or not, remember to apply for HFE before you #BTOgether. Read the guide on how to apply for an HFE letter.

Hashtags

HDB

@SingaporeHDB · Post #1328 · 02.08.2022 г., 02:00

🏠 Gearing up to #BTOgether? 💰 Learn how to assess your financial fitness, plan for a home purchase, and plan ahead for your life as a couple at the Institute of Financial Literacy’s free financial planning workshop!

Hashtags

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