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

Резултати

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

Пребарај: #texturesofthecity

当前筛选 #texturesofthecity清除筛选
URA Singapore

@URASingapore · Post #474 · 04.10.2022 г., 04:03

👀🍬 If you’ve been enjoying all that eye candy of the city's architecture on our feed recently, you have these five volunteers of ours to thank! Hit play to find out what got them started on the #TexturesoftheCityexhibition, as well as how excellent architecture and design in Singapore continues to serve as inspiration for their craft! 📸 🤝 Interested to curate and present exhibitions at the Singapore City Gallery's City Canvas? Join us as a URA volunteer and get involved in shaping our city together with us! Other opportunities include building and remaking community spaces, leading community tours at the Singapore City Gallery, and more! Sign up at: go.gov.sg/uravp

URA Singapore

@URASingapore · Post #468 · 20.09.2022 г., 09:40

🎉 Congratulations to our giveaway winners, Noorsyahidah and Rowell – instructions on how to claim your prizes are on their way to your inboxes! From now till 15 Oct, you can also treat yourself to a visual journey through the city at our #TexturesoftheCity exhibition, now on at the Singapore City Gallery. Featuring stunning photography by URA volunteers, the free exhibition explores award-winning architecture around Singapore, while uncovering the innovative design innovations that have inspired fresh ways for us to live, work, play and move. 🤸‍♀️ 📸☝ Tap in for a preview, and plan your visit at go.gov.sg/totc-exhb Photo credits: Aaron Lai, Dennis Fajardo, Fallon Thng, Lawrence Pang, & Ng Wee Liang

URA Singapore

@URASingapore · Post #448 · 06.09.2022 г., 04:02

[NOW ON AT THE SINGAPORE CITY GALLERY] Go on a visual journey through the city with five of our volunteer photographers at our latest #TexturesoftheCity photo exhibition! From stunning captures of skyscrapers to school buildings, the exhibition showcases how good design plays an important role in unlocking even more possibilities in land-scarce Singapore. ☝ Explore how thoughtful design and architecture have inspired new ways in which we learn, work, and recharge, and plan your visit to the exhibition at: go.gov.sg/totc-exhb 📸 Photo credits: Ng Wee Liang, Dennis Fajardo, Aaron Lai, Lawrence Pang, and Fallon Thng

URA Singapore

@URASingapore · Post #424 · 15.08.2022 г., 04:14

📢 [New exhibition to check out!] See our city through a different light at our latest exhibition at the Singapore City Gallery! Unravel the #TexturesoftheCity through the lens of five of our volunteer photographers and discover how award-winning design has been thoughtfully weaved throughout our city to enable inspiring spaces that have changed the way we live, work, play, and move. 📸 Catch it at the Singapore City Gallery from now till 15 October 2022. Find out more at go.gov.sg/totc-exhb

URA Singapore

@URASingapore · Post #298 · 15.04.2022 г., 05:00

Did you know that the Novena Church’s actual name is the Church of St Alphonsus? Since then, it’s become more popularly known as the Novena Church. The word “Novena” derives from "nine" in Latin, referring to the Catholic Church's nine days or weeks of devotion. After being gazetted for conservation in 2011, the historic building was closed for substantial restoration work before reopening in 2017. The architecture of the structure is influenced by the Bible scriptures of King Solomon's temple, with a Gothic-inspired look that reflects the religion's early years. This historic landmark along Thomson Road remains a local landmark and community touchstone for all. Swipe through to view more about its architectural details, and blessed Good Friday to all! 🧡 #texturesofthecity

URA Singapore

@URASingapore · Post #240 · 15.02.2022 г., 10:02

Jurong Town Hall is a building that retained the zeitgeist of Singapore’s industrialisation and transformation. Constructed in 1974, this iconic building served as the headquarters of JTC until 2000, housing many visionary minds that worked to improve the lives of Singaporeans throughout our nation-building. The winner of the 2018 Architectural Heritage Award has since been gazetted as a national monument and refurbished as a key landmark in Jurong – currently serving as a hub for trade associations. The building’s nautical elements are thought to be inspired by vessels at the Jurong Shipyard Corporation, giving the building the appearance of a ship’s hull with the clock tower as its mast. Click through the pictures above to view more! #texturesofthecity

URA Singapore

@URASingapore · Post #166 · 04.11.2021 г., 04:00

Happy Deepavali to all celebrating the Festival of Lights! 🪔 Today, we drop by Little India to discover some of the art within the historical district’s hidden spaces that not only pays homage to Hindu heritage and culture, but also celebrates our multicultural and multi-religious nation. Fun fact: Many of these pieces feature a contemporary twist by the artist to blend modern and traditional art forms. Click through to check them out! Do you know of any other sculpture and murals in the area? 😀 #texturesofthecity

URA Singapore

@URASingapore · Post #142 · 31.08.2021 г., 15:03

The 'lungs of the city' were what planners likened historic districts to when they proposed the conservation of these significant areas back in the 1980s. Ever wondered why this was so? Find out as you explore today's #TexturesoftheCity feature inspired by the vibrant streetscapes of Little India!

URA Singapore

@URASingapore · Post #112 · 31.03.2021 г., 13:53

Have you seen these #TexturesoftheCity? This bold architectural feature connects two historic buildings in Singapore – both of which have been restored and elegantly transformed into a visual arts exhibition space. Can you guess where?

URA Singapore

@URASingapore · Post #100 · 02.03.2021 г., 14:13

Have you seen these #texturesofthecity? Besides a futuristic-looking facade, another notable feature found in this building's surrounding spaces is the use of vertical greenery. Find out where!🔍

URA Singapore

@URASingapore · Post #273 · 18.03.2022 г., 10:00

What does the neighbourhood of Bukit Pasoh have in common with pottery? The area was once known for the trade of distinct earthenware pots, popular with the households living around the area, thus the name Bukit Pasoh was born. Today, Bukit Pasoh is a modern mixed-use area that retains key elements of its past. If you walk along Neil Road, Bukit Pasoh Road, and Keong Saik Road, you’ll be able to spot many conserved clan associations, restaurants and bars that integrate their original shophouse exteriors with modern and chic interiors. Click through the pictures above for some highlights of the area! If you enjoy exploring different neighbourhoods in Singapore, check out our newly launched “Love Local” book, created in partnership with Time Out: go.gov.sg/lovelocalguide. You can also head over to timeout.com/singapore/love-local to see more! #architecture#TexturesoftheCity #heritagebuildings#shophouses