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

Резултати

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

Пребарај: #laws

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

@balinews · Post #419 · 27.05.2025 г., 16:25

💰Indonesia is preparing a tough law against corruption 📰 Indonesian President Prabowo Subianto supported the bill on confiscation of assets gained by criminal means. The new law will allow seizing assets from corrupt officials even if their origin is not proven in court. ➡️ This could be a breakthrough in the fight against embezzlement and return billions of rupiah to the budget. ℹ️ The Asset Forfeiture Bill (RUU Perampasan Aset) has been under discussion for years. Support at the presidential level could be a decisive step to get the document passed. #laws@BaliNews

Hashtags

Bali News

@balinews · Post #469 · 02.08.2025 г., 13:40

🏝Bali continues to sweep the coastline of illegal buildings 👮‍♂️Balangan is next. The area risks repeating the fate of Bingin: the authorities have already counted 23 cafes, warung and surf school, built without permits. 🚧 Now the documents are being checked, and only after the decision of the regional parliament will heavy machinery be able to move from Bingin to this beach - tentatively not before the end of August. #places#laws@BaliNews

Hashtags

Bali News

@balinews · Post #167 · 08.09.2024 г., 14:59

🥳'Enough of your parties': Bali wants to ban partying in Bali 📰 Coordinating Minister for Maritime Affairs and Investment Luhut Binsar Panjaitan said he is concerned about the huge number of foreigners coming to Bali. ❌ The main issue the government wants to focus on is the same – respect from foreigners for the local culture and way of life. The minister has explicitly called for stricter party laws. We also don't want villas to become party venues and people dancing virtually naked in clubs. We will not let them do that. Enough of your parties. @BaliNews #tourism#laws

Bali News

@balinews · Post #76 · 04.06.2024 г., 11:00

🚯‘Bali doesn't need a rubbish tourist’: Balinese demand stricter controls on foreigners Dozens of angry social media posts from outraged Balinese forced Indonesian Minister of Tourism and Creative Economy Sandiaga Uno to calm the public. The minister reiterated the need to hold foreign visitors strictly accountable if they break the rules. This applies to tourists, investors and foreign business owners. 📞 The Directorate General of Immigration of the Ministry of Law and Human Rights has opened a hotline for people who want to report suspicious activities or legal status of foreign nationals. The head of the department, Saffar Muhammad Ghodam, said the alert line is operated by the information and complaints service for immigration monitoring and enforcement activities. Reporting any information, including unverified information, is encouraged to 📱 (+62)81399679966. ‘This immigration monitoring and enforcement hotline allows the public to lodge complaints against foreigners suspected of violating immigration rules,’ Saffar said in an official statement. @BaliNews #tourism#laws

Bali News

@balinews · Post #22 · 23.04.2024 г., 12:32

👮 Bali has started spot check drug tests on tourism drivers Bali has introduced spot-check drug tests on tourist drivers at top tourist attractions on the island. The first spot checks were conducted on Friday, April 19th. The spot checks are part of a wider mission to crack down on the use of drugs and tourist service providers driving and conducting work activities under the influence. @BaliNews #laws#tourism

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40490 · 06.01.2026 г., 19:02

A man is forbidden to kiss a woman while she’s asleep in Logan County, Colorado USA, making a "Sleeping Beauty" scenario illegal, though it's more of a quirky local legend than actively enforced statute. @googlefactss#laws#usa

Hashtags

Bali News

@balinews · Post #433 · 11.06.2025 г., 11:10

📰Bali tightens measures against reckless tourists Speeding will result in deportation. 👮‍♂️ The hunt for reckless drivers is underway in Bali: one serious speeding offense, riding without a helmet, or performing stunts on a motorcycle will now result in deportation without warning, rather than a fine. 📍 The police and immigration service are already conducting night raids in Chang and Uluwatu, confiscating motorcycles and checking riders. It's time to clean up the island of people who don't respect others, but above all themselves... #transport#laws@BaliNews

В РБК вышла моя колонка с критикой обсуждаемого законопроекта по регулированию почтовых сервисов [1]. Самые неприятные последствия что этого что других запретительных законов - это падение привлекательности российской юрисдикции для любых интернет проектов. При таком регулировании цифровой экономики не будет. Ссылки: [1] https://www.rbc.ru/opinions/politics/14/10/2019/5da033ea9a79478f25ca783c #laws#runet

Hashtags

Bali News

@balinews · Post #157 · 31.08.2024 г., 04:00

📱Indonesian authorities are preparing to block Telegram 📰 The country's Minister of Communications and Information Budi Aryeh Setiadi said that Telegram is one step away from being blocked on the territory of Indonesia. All because of its refusal to co-operate with law enforcement. We have warned Telegram twice, because on this platform there is a mass distribution of not only gambling, but also pornography. said Budi Aryeh Setiadi at the Jakarta Communications and Information Office. 🤞 However, the communications and information minister did not give an exact timeline for when Durov's messenger will be out of Indonesian laws. At the moment it is known about two letters that the Indonesian authorities sent to the Telegram office. In addition, an investigation is ongoing. And it is on its results, apparently, that the verdict that will be handed down to the messenger will depend. @BaliNews #accidents#laws

Bali News

@balinews · Post #104 · 30.06.2024 г., 04:01

🕵🏼Mass capture of cybercrime suspects occurred in Bali 👮‍♂️ Indonesian authorities detained more than a hundred foreign nationals. This massive operation was carried out by the Bali Becik unit, which is the name of a special branch of immigration enforcers in charge of controlling foreigners who break the law. Part of the immigration team conducted surveillance at a villa in Marga neighborhood, Tabanan regency. 💻 The detainees had no official documents and they all had expired visas. In addition, numerous computers and cell phones were found at the scene, indicating likely cybercriminal activity. @BaliNews #accidents#laws

Bali News

@balinews · Post #467 · 30.07.2025 г., 08:45

📰Yoga for donation is a direct route to deportation from Bali ℹ️ A yoga and freediving trainer was deported from Bali after immigration saw announcements on his social media accounts of “yoga-for-donation” classes and deemed them illegal work. Officers found out that the foreigner only had a tourist visa, which does not authorize him to conduct commercial activities. 👮‍♂️ Bali tourists should remember: any work without authorization will cost the foreigner deportation and entry ban. #laws#free@BaliNews

Hashtags

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