Можно ли в 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
🌊 The most dangerous path to one of the most beautiful beaches in the world
📍 Kelingking Beach isn’t just a viewpoint – it’s an experience. From the top of the iconic T-Rex-shaped cliffs to the crystal-clear waters below, every step (or dive) is pure adrenaline.
#beaches#places@BaliNews
📍Tanah Barak
🏝️ A road carved between massive limestone cliffs, and it suddenly opens up to a pristine beach. Right next to it is Green Bowl Beach – another unreal spot.
🛵 Getting there is easy: rent a scooter or car and head toward Uluwatu (Bukit Peninsula). From there it’s about 25–30 minutes. Parking is right by the beach. Green Bowl is just 5 minutes away, but be ready for a long staircase down.
#places#beaches@BaliNews
🏗 The demolition of a controversial 182-metre glass lift at Kelingking Beach in Nusa Penida
🤬 The lift had tourists and locals in uproar, with many complaining it was spoiling the location’s natural beauty.
#places#beaches@BaliNews
📍Melasti Beach is the place where turquoise waters meet towering cliffs and white sand stretches for miles.
Perfect for relaxing, swimming, and catching unforgettable sunsets. A peaceful paradise away from the crowds.
🛵Quick travel times (without heavy traffic):
From Ngurah Rai Airport: ~30 min
From Kuta/Seminyak: ~45–60 min (~19–22 km)
From Canggu: ~1.5–2 hours
From Uluwatu area: ~20–30 min
From Ubud: ~1.5–2.5+ hours (traffic can add a lot)
#places#beaches@BaliNews
🏝Bali's beaches are going underwater at a record rate
🔎 Experts at the Regional Marine Research Centre have concluded that Bali's coastline is shrinking faster than the global average.
🌊 The total length of the island's coastline, which was 668.84 kilometres in 2016, has shrunk to 662.59 kilometres by 2022. It turns out that Bali is losing 1.21 metres of beach area per year.
📈 The researchers arrived at these figures using geospatial data. The last calculation of the coastline from 75 separate monitoring points was done in March 2023, and it only confirmed this trend.
📍 The highest level of shoreline destruction due to erosion is seen in the south, west coast and southeast of Bali. Beaches in the provinces of Jembrana, Tabanan, Badung, Denpasar, Gianyar, Klungkung and Karangasem have been most affected.
@BaliNews
#statistics#beaches
🏝Indonesia's beaches listed the world's best beaches
Each year Banana Boat sponsors a list of the 50 best beaches in the world. More than 1,000 experienced travelers from around the world participate in the process. They are asked to choose the place they visited themselves that impressed them the most.
Indonesian beaches took two places at once in the 2024 ranking:
🏝 # 7 - Pink Beach
🏝 # 39 - Kelingking Beach
The best thing is that it is very easy to get to them from Bali.
@BaliNews
#beaches#statistics
🌊 Kuta beach will be restored after the storm
📍 The recent two-meter high tidal waves that hit Bali left a mark on one of the most popular beaches on the island, Kuta.
🏖 The sandy coastline has been badly eroded, making it virtually unfit for walking.
📰 Now, new breakwaters are planned to be built. It is expected that the authorities will begin work to restore the beach this month, but for now the beach and small businesses on it are being helped by locals and tourists. Together they have decided to cope with coastal erosion.
@BaliNews
#beaches#Kuta
🚯 Bingin Beach covered in construction debris — locals are frustrated
🧱 Over 40 cafes, bars, and guesthouses were demolished on the slope of Bingin in Uluwatu. Three months later, the debris is still lying around. Some of the concrete, bricks, and wood were simply buried in the sand. Officials claim that heavy rains wash the debris downhill — it’s natural erosion, not “burial.”
🚜 Machinery has stopped due to a lack of budget. Cleanup is now done manually while awaiting additional funding.
#places#construction#beaches@BaliNews
📰Illegal structures found in Melasti and scheduled for demolition
🏝 Eight structures in violation of zoning regulations have been identified on Melasti Beach, including beach clubs and cafes that are too close to the ocean, in a protected coastal area, and partially on municipal land. The owners have already been sent repeated official warnings, and the documents have been forwarded to the public order service for further action.
🧐 The administration's approach is now softer than in Balangan: Melasti will be “discussed and carefully studied” rather than “demolished on the spot.”
#places#beaches#Badung@BaliNews
🏖 Tourists asked to pay cash “entry fee” to reach free Dreamland Beach
📰 In Uluwatu, tourists reported being asked to pay cash for “entry” on the way to free Dreamland Beach — with no ticket booth and no receipt.
ℹ️ The story went viral after a video spread online, and officials from South Kuta conducted an inspection. However, they didn’t find the so-called “ticket booth” on site.
🆓 The traditional Pecatu community stated that there is no official entrance fee, and urged visitors not to give in to such requests.
⚠️ If this happens to you, record it and report it to local authorities.
#tourism#scam#beaches@BaliNews
🏝The upgrading of Candidasa beach will last until the end of 2026
📰 Bali authorities are undertaking the improvement of Candidasa beach in Karangasem. It has long been firmly favored by numerous low-cost hotels. Construction work seriously interferes with tourists to rest. And the renovation will last until the end of 2026.
🌅 Tourists will be able to enjoy sunsets, walks along the beautiful promenade and get more comfortable access to the sea. After the improvement, a decent strip of sand should appear on the beach.
@BaliNews
#beaches#tourism#Karangasem
🪧The Balinese public has spoken out against the new beach club in Sanur
🙅♂️ No sooner have locals gotten used to the new shopping center in Sanur, now they have to defend the beach as well. Bali Icon Mall opened in June 2024, but not completely - the promised beach club was decided to be completed later. This construction is what the Balinese people oppose.
📰 The population fears that this development could affect the people who choose Sanur as their vacation destination. And if noisy young people flock here, pensioners and families with children may not like it, reports detikbali.
@BaliNews
#beaches#Sanur#Denpasar