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

Резултати

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

Пребарај: #dmp2025

当前筛选 #dmp2025清除筛选
gov.sg

@Govsg · Post #1807 · 14.10.2023 г., 04:11

Making Singapore a liveable, inclusive and endearing home for all takes a collective effort. Learn how you can contribute to the Draft Master Plan 2025 and shape your future Singapore here: go.gov.sg/URADraftMasterPlan #DMP2025 Infographics: @urasingapore

Hashtags

URA Singapore

@URASingapore · Post #610 · 05.10.2023 г., 11:12

[JUST LAUNCHED] Join us in shaping our city in the Draft Master Plan 2025 Public Engagement! Long-term planning has shaped the city that we live in today. Now, you too can play a part in making Singapore a more liveable, inclusive and endearing home. We will be engaging Singaporeans over the next two years on various plans and the public engagement exercise will culminate in the Draft Master Plan 2025, which will guide Singapore’s development over the next 10 to 15 years. Find out more at: https://go.gov.sg/DMP2025videotg #DMP2025

Hashtags

URA Singapore

@URASingapore · Post #1228 · 12.06.2025 г., 10:05

Who says uncles can’t keep up? 🏙💪 Meet Team Strong Silvers, your friendly neighbourhood uncles who aren't just staying active; they inspire an entire community to move! Watch how this group of friends show us what ageing-in-place looks like - turning everyday spaces into pockets of connection. Want more neighbourhoods like this? The URA Draft Master Plan 2025 is shaping spaces where we can all age strong and live well. Learn more: go.gov.sg/ExtraordinaryStoriesTG✨ #DMP2025#SpaceForOurDreams

URA Singapore

@URASingapore · Post #1210 · 20.05.2025 г., 10:01

Will Singapore ever run out of land? 👀 We get this question a lot—so we got Navin, our Urban Planner, to break it down for you. From sky gardens to underground links, see how we’re planning ahead to make room for all the things that matter—homes, recreation, green spaces, your dreams and aspirations. 🌇🌿 Share with us your ideal Singapore in the next 10 to 15 years here: go.gov.sg/URAPlannerExplainsTG and keep an eye out for our upcoming exhibition in June! #DMP2025#SpaceForOurDreams

URA Singapore

@URASingapore · Post #1201 · 24.04.2025 г., 10:03

This is our type of ASMR. 😌 👣 Active Living: Move freely and with ease on walkable pathways. 🌻 Social Well-Being: Bond with your community in shared spaces. 🌳 Mental Wellness: Discover peaceful parks near home to relax and unwind. ☁️ Routine: Everyday wellness, wherever you are. Check out our newest Urban Lab exhibition at: go.gov.sg/HealthyCitiesTG Well-Being in the City: Innovating Healthy Living 📅: 1 Apr - 31 May 2025 📍: The URA Centre, Level 1 Atrium #DMP2025#SpaceforOurDreams

URA Singapore

@URASingapore · Post #1159 · 06.03.2025 г., 10:00

Ever wondered who decides what gets built in Singapore? 🤔 It's not just professionals and government agencies—you can contribute too! Join Davina, our Urban Planner, as she unveils how the land planning process works in Singapore. Got ideas to shape your neighbourhoods or workspaces? 💡 Visit go.gov.sg/URAPlannerExplainsTG to see what’s planned for the Draft Master Plan 2025 and share your thoughts! #DMP2025#SpaceForOurDreams

URA Singapore

@URASingapore · Post #1144 · 04.02.2025 г., 10:03

Big things are happening at the Rail Corridor with new community nodes coming your way! Think chill spots, and heritage gems getting a fresh spin. 🌿✨ Watch to see what’s shaping up, and swing by the 'From Rail to Trail' Rail Corridor Exhibition to check out more. 📅: Now till 28 Feb 2025⁣ 📍: URA Centre 👉 Share your ideas at: go.gov.sg/RCexhibitionTG #SpaceForOurDreams#DMP2025

URA Singapore

@URASingapore · Post #1125 · 17.01.2025 г., 03:20

Take a stroll down the Rail Corridor with URA's Senior Director of Planning, See Nin, and wildlife documentary camerawoman, Evangelista, as they reveal how this 24km stretch of passageway was transformed from tracks 🛤 to trails 👣 – while preserving its distinctive character! This isn't just another makeover; we're talking about over 50 access points connecting neighbourhoods across our sunny island! 💭 The journey continues, and we want to hear from you! Join us at the Rail Corridor Exhibition happening from 17 Jan at the URA Centre! Find out more on go.gov.sg/RailCorridorTG #DMP2025#SpaceForOurDreams

URA Singapore

@URASingapore · Post #1114 · 06.01.2025 г., 10:06

Swipe to see how Punggol Digital District is transforming into Singapore’s first smart district. With community spaces, green paths and integrated work-live-play environments, it’s taking urban living to the next level! Read more at go.gov.sg/PDDarticleTG. Keep a lookout for the Draft Master Plan 2025 exhibition happening in June, where we will be seeking your ideas on more business and job nodes across Singapore! Image credits: JTC Corporation #DMP2025#SpaceForOurDreams

URA Singapore

@URASingapore · Post #1096 · 28.12.2024 г., 04:01

Creating a more liveable, inclusive, and endearing Singapore — that’s the goal of the Draft Master Plan 2025, and we’ve made great strides this year. Here’s our 2024, wrapped! For more info, visit go.gov.sg/URADraftMasterPlanTG #DMP2025#SpaceforOurDreams

URA Singapore

@URASingapore · Post #1082 · 18.12.2024 г., 10:09

Imagine your future, supercharged ⚡🔋 ⁣ Check out how plans for our Northern and Central areas' business nodes will mean even shorter trips to work, more innovative spaces to learn and collaborate, and lively, green neighbourhoods to live your best life! ⁣ Last chance to explore these transformations and more at our ‘Enabling Sustainable Growth: Shaping the Future of Work’ exhibition! 📅: Now till 3 Jan 2025⁣ 📍: URA Centre 👉 More info: go.gov.sg/FutureofWorkTG #DMP2025#SpaceForOurDreams

URA Singapore

@URASingapore · Post #1064 · 10.12.2024 г., 10:01

Smarter. Faster. Greener. Discover innovations that are shaping the future of last-mile deliveries. 💡 Singapore is shaping the future of last-mile deliveries with AI, robots and innovative designs. Don’t miss out on seeing it all in one place! 📅: Now till 25 Jan 2025⁣ 📍: URA Centre 👉 Free guided tours and more at: go.gov.sg/DeliveringtheFutureTG #DMP2025#SpaceForOurDreams

123•••1011
ПретходнаСтраница 1 од 11Следна