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

Пребарај: #tabanan

当前筛选 #tabanan清除筛选
Bali News

@balinews · Post #226 · 26.10.2024 г., 11:15

🌾Jatiluwih rice terraces prepare to launch laser show 🎆 The famous Jatiluwih Rice Terraces in Tabanan, a UNESCO World Heritage Site, will delight tourists with a nighttime laser show. 🌅 The aim of this project is to make the rice terraces attractive to visitors even after 6pm. Usually it is quiet after sunset and all cafes and stores are closed. 🔜 The show is scheduled to officially open to the public from December 1, 2024. @BaliNews #places#Tabanan

Bali News

@balinews · Post #479 · 16.08.2025 г., 13:55

🔥Fire at Ulaman Eco Luxury Resort: bamboo resort in Tabanan burned down 📰 One of the island's most famous eco-resorts, Ulaman Eco Luxury Resort, burned down in Tabanan. The flames engulfed the buildings during the day, and strong winds accelerated their spread. The fire was clearly visible from afar, as the complex is located in rice fields. 👩‍🚒 Seventeen bamboo villas were destroyed. Fortunately, none of the residents were on site at the time of the fire. #accidents#Tabanan@BaliNews

Bali News

@balinews · Post #332 · 26.02.2025 г., 07:04

📰Helicopter pad near Jatiluwih fields to open in March 🌾 The Jatiluwih Rice Terraces, a UNESCO World Heritage Site, will have a helipad. The helipad for VIP visitors to the attraction has already been constructed and the official opening will take place in March 2025. 🚁 At the moment, the period of testing and trial landings has been completed. The helipad will have no impact on the protected landscape and the rice terraces themselves. @BaliNews #transport#places#Tabanan

Bali News

@balinews · Post #482 · 20.08.2025 г., 13:15

🛕Tanah Lot Arts and Culture Festival at Pura Tanah Lot Temple 📆 On August 22 (Friday), the festival will bring together spectacular performances, music, cuisine, and an atmosphere imbued with the spirit of the island. 📍 Tanah Lot Temple is one of the nine main sacred temples of Bali. It is protected by UNESCO. Thousands of tourists come every day to see this amazing place. 🌅 Guests will enjoy vibrant cultural performances: traditional dances, the mesmerizing sounds of gamelan, and the main symbol of the festival – the colorful Gebogan parade, taking place against the backdrop of the sunset sky. #events#culture#Tabanan@BaliNews

Bali News

@balinews · Post #416 · 24.05.2025 г., 12:25

🍿Free movie nights every Monday 📍 Ash Nuanu, Tabanan ⏰ 7:30 pm 🎫 Cult films, cozy vibes, craft beer, and pizza. Register free to save the spot. #events#wheretogo#free#Tabanan@BaliNews

Bali News

@balinews · Post #149 · 22.08.2024 г., 12:00

🍛Where to try rare Balinese dishes this weekend? 🧑‍🍳 Already this weekend, from August 23 to 25, an art and cooking festival will be held at Tanah Lot Temple in Tabanan. The organizers promise not just to open a food court, but to treat visitors to rare masterpieces of Indonesian cuisine. 🌅 All three days of festivities will be organized and conducted by the efforts of the people of 23 traditional villages. At sunset, they will participate in a very colorful traditional Gebogan parade with the theme “Sunset in Paradise”. @BaliNews #wheretogo#events#festivals#Tabanan

Bali News

@balinews · Post #247 · 25.11.2024 г., 13:45

🪩21-meter immersive sphere The Dome Experience opened in Bali 🔎 A rather interesting interactive object has appeared in Bali. This is The Dome Experience by Labyrinth Collective. The company has built a huge dome with a diameter of 21 meters, inside which there is a screen with an area of 600 square meters. 🔊 484 powerful speakers with a total length of 60 meters are installed behind the screen in a circle. Inside, in the center of the hall is a stage for performances. In addition to the visual and powerful sound spatial effects, the audience will also be treated to a show presented by dancers. 📍 The dome is located at Luna Beach Club within the new conceptual innovation village Nuanu. It is a “creative city” project in Bali, next to Nyanya Beach in Tabanan district. 📆 The sessions are held every Wednesday and Saturday from 11 am to 12:30 pm and tickets can also be purchased online at IDR 490,000 for tourists. 📱labyrinthartbali @BaliNews #wheretogo#places#entertainment#Tabanan

Bali News

@balinews · Post #300 · 25.01.2025 г., 10:25

📰Alit Saputra public sports complex opened in Tabanan 📍 The renovation of the Alit Saputra sports ground in Tabanan has been completed. The look of the former soccer field has changed beyond recognition. 👍DC Field, dirty and neglected, especially during the rainy season, has now become a modern and lively sports complex. 🏋️‍♀️ It has sports equipment, kid's play areas, and picnic and activity areas. Even in rainy weather, you can exercise on the treadmills. 🫔 Along the edge of the complex, vendors offer local traditional snacks, creating a real street party atmosphere. @BaliNews #goodnews#places#wheretogo#sport#Tabanan

Bali News

@balinews · Post #92 · 17.06.2024 г., 15:27

🚍 An electric bus for tourists has come up at Jatiluwih 🍚 The Jatiluwih rice terraces have a new option for tourists. They can now use electric shuttle buses to explore this unique area. 👥 At the moment, these vehicles can accommodate 14 people. Tourists will be able to drive from the parking lot through the rice fields in a quiet and eco-friendly vehicle, enjoying the silence and fresh air. ⛰️ The Jatiluwih Rice Terraces are located in Tabanan District and are recognized as a UNESCO World Heritage Site. They are located on the slopes of Mount Batukaru and cover an area of about 303 hectares. @BaliNews #wheretogo#goodnews#places#Tabanan#Jatiluwih

Bali News

@balinews · Post #208 · 11.10.2024 г., 04:37

🎉The biggest family festival in Bali this Saturday 👨‍👩‍👧‍👦SAMANA Festival is a vibrant family festival in Nuanu City, taking place on October 12th, 10:00 – 18:00. 🥳 This annual event offers an unforgettable day of fun, creativity, and togetherness, designed to bring families closer through a variety of activities and experiences tailored for children of all ages. The festival will feature lots and lots of activities, programs, entertainment, and shows for you to enjoy thoroughout the day. 🎫 Tickets are available to buy here, they start from 55 Rp. @BaliNews #wheretogo#events#kids#entertainment#Tabanan

#Indonesia#Bali#Tabanan#Flood#weather#climate#destruction#anomaly#climatechange 🇮🇩 Сильное наводнение на Бали 🌧🌊🚨 22 апреля 2026 года сильные дожди вызвали серьезное наводнение в Банджаре Лодаланге, деревни Кукух (район Марга, провинция Табанан, Бали, Индонезия). Наводнительные воды затопили дома и сельскохозяйственные угодья, а дороги были заблокированы. Жители сообщили о повреждении имущества и перебоях в транспорте. Власти развернули экстренные службы для эвакуации пострадавших и смягчения последствий катастрофы.