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

Резултати

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

Пребарај: #yearofpublichygiene

当前筛选 #yearofpublichygiene清除筛选
NEA Singapore

@NEASingapore · Post #930 · 05.11.2024 г., 01:02

🎮 Singapore River Quest: Level Up IRL 🎮 Ready to game outside your room? 🧩 12 puzzles to crack 🏆 Prizes up for grabs 🏙️ Level up your knowledge of the SG River and its history Play solo or grab your squad and explore this outdoor game. More deets: go.gov.sg/singapore-river-quest #KeepSGClean#YearofPublicHygiene

NEA Singapore

@NEASingapore · Post #862 · 20.07.2024 г., 01:01

🌴 It's always a treat to take a stroll around Marina Bay Sands in the evenings. If you are heading there to catch the fireworks during NDP previews, don’t forget to bin your litter properly while enjoying the view. Together, let’s #KeepSGClean! #YearOfPublicHygiene

gov.sg

@Govsg · Post #2342 · 26.07.2024 г., 07:09

Ever wondered what happens after a waste truck collects your waste? 🚮🚮🚮 With current disposal rate, Semakau Landfill is projected to reach full capacity by 2035. 🗑️🗑️🗑️ Let’s take action towards a more sustainable Singapore - say yes to reducing waste and do your part today! 👏🏻👏🏻👏🏻 #KeepSGClean#YearofPublicHygiene

NEA Singapore

@NEASingapore · Post #784 · 04.03.2024 г., 12:43

#SGBudget2024 Opening of Singapore’s first Enviro Tech Innovation Hub in Apr 2024 – an industry-led collaboration to advance sustainable environmental cleaning and integrated facilities management; and support the cleaning workforce. More info at www.nea.gov.sg/year-of-public-hygiene#YearofPublicHygiene

NEA Singapore

@NEASingapore · Post #783 · 04.03.2024 г., 12:42

#SGBudget2024 To keep the incidence of vector-borne diseases low, we will focus on tackling rat issues at source and combating dengue by expanding Project Wolbachia - Singapore. More info at www.nea.gov.sg/year-of-public-hygiene#YearofPublicHygiene

NEA Singapore

@NEASingapore · Post #780 · 04.03.2024 г., 12:09

#SGBudget2024 The Ministry of Sustainability and the Environment has designated 2024 as the #YearofPublicHygiene to galvanise all to reinforce good hygiene practices for our collective well-being. In this year, we will: ✅ Continue to reinforce high standards of public hygiene ✅ Step up efforts across 5 key areas More information at www.nea.gov.sg/year-of-public-hygiene

NEA Singapore

@NEASingapore · Post #988 · 02.02.2025 г., 01:02

Happy World Wetlands Day! Wetlands are vital ecosystems that support a rich variety of wildlife! 🦀🦦🌱 As you wander through the wetlands of #StunningSingapore, such as the Sungei Buloh Wetland Reserve, be a gracious guest and bin your litter properly. Let’s do our part to #KeepSGClean and safeguard our wetlands for future generations. #YearofPublicHygiene

NEA Singapore

@NEASingapore · Post #956 · 23.11.2024 г., 01:03

👨‍👩‍👧‍👦 Holiday Fun Pick - Play:Date exhibition at National Museum of Singapore 🏛️ As we marvel at the exhibitions and architecture of our oldest museum, let's play our part in preserving its beauty by keeping it litter-free. #StunningSingapore#KeepSGClean#YearofPublicHygiene

NEA Singapore

@NEASingapore · Post #853 · 06.07.2024 г., 03:22

🌴✨ Discover the serene beauty of Singapore Botanic Gardens. Admire the water lilies floating on a stunning lake amidst picturesque palm trees. Our #StunningSingapore spaces are truly breath-taking, and it's up to us to keep them that way! Let's ensure these public spaces stay litter-free and clean. #KeepSGClean#YearofPublicHygiene#StunningSingapore

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