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

Резултати

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

Пребарај: #us

当前筛选 #us清除筛选
Islamic World News

@iswnews_en · Post #17858 · 29.03.2026 г., 00:10

🇺🇸‼️ Million-man protests in America against Trump with the slogan "No Kings" ➡️Millions of Americans gathered in Washington, Boston, New York, Chicago, Philadelphia, Atlanta, San Francisco, and dozens of other cities across the United States to protest against the policies of the Trump administration, holding massive demonstrations. 🔺These protests are among the largest and most unprecedented in the US in recent years. Protesters at these gatherings chanted "No to Kings," objecting to rising fuel and public service costs while opposing the warmongering policies of the Trump administration, particularly the war with Iran. ✍️ Trump, who a month ago claimed to be helping the Iranian people by instigating unrest in Iran, is now mired in dealing with his own domestic troubles and cannot rescue the American people from their economic and livelihood struggles. Poor Zionist settlers, Arab governments, and the Iranian opposition who had pinned their hopes on Trump's America! #US

Hashtags

Islamic World News

@iswnews_en · Post #17701 · 26.03.2026 г., 11:37

You the cowardly weaklings! we have been waiting for days for you to set foot on this soil so that we avenge every single child you unjustly killed. Come, we eagerly await that moment to tear out your throats. We are waiting for you!#US

Hashtags

Islamic World News

@iswnews_en · Post #17626 · 24.03.2026 г., 16:15

🇺🇸‼️ USS Gerald Ford aircraft carrier taken out of service for 14 months! ➡️ The aircraft carrier USS Gerald Ford of the U.S. terrorist army has been taken out of service for approximately 12 to 14 months due to a fire in its laundry section. Over the past week, this aircraft carrier was stationed in the Red Sea off the coast of Jeddah. 👉 Following the fire aboard the carrier, which took about 30 hours to bring under control, the Gerald Ford changed course toward the Greek island of Crete. According to the latest information, it crossed the Suez Canal yesterday. #US

Hashtags

Islamic World News

@iswnews_en · Post #17595 · 24.03.2026 г., 08:57

🇺🇸🔥 Explosion and fire at the Valero refinery in the United States 🔹 A large explosion and fire occurred at the Valero refinery in Port Arthur, Texas. Local authorities cited a technical fault in an industrial heater as the cause of the explosion, but the incident was likely the result of sabotage. ✍️ The Valero refinery is one of the largest refineries and vital infrastructure facilities in the United States, with a capacity to refine approximately 435,000 barrels of crude oil per day. The main function of this refinery is to convert crude oil into fuel products such as gasoline and jet fuel. #US

Hashtags

VDARE.com

@vdare · Post #13839 · 17.01.2025 г., 14:06

🇺🇸 MS-13 member pleads guilty to slaying of 2 girls and 5 others in New York A high-ranking member of an MS-13 clique in New York pleaded guilty Tuesday to racketeering and other federal charges in a case involving seven slayings, including the 2016 killings of two high school girls that focused the nation’s attention on the violent Central American street gang. Jairo Saenz, 28, entered the plea in federal court in Central Islip in a hearing attended by members of his family and some of the victims’ families. Saenz, who is originally from El Salvador, will be sentenced June 13 and faces 40 to 60 years in prison as part of the plea deal approved by the judge. 🔎Source #US ☠️ Blood Meridian

Hashtags

VDARE.com

@vdare · Post #13782 · 03.12.2024 г., 01:45

💰2 Canadians arrested for drug trafficking; $40 million of cocaine seized from truck in Illinois Two people from Canada have been arrested on drug charges, after Illinois State Police seized more than $40 million worth of cocaine from a semi-trailer truck near the Iowa state line on Friday. Police arrested 27-year-old Vanshpreet Singh and 36-year-old Manpreet Singh, both from Ontario, Canada. "Canadians" #US 🍁Maple Chronicles

Hashtags

VDARE.com

@vdare · Post #13505 · 04.08.2024 г., 13:48

🇺🇸Proposed law pushes for tougher migrant detention following Texas girl’s killing Family members of a 12-year-old Houston girl who was killed by two Venezuelan men who entered the U.S. illegally said Friday that they are supporting legislation that would severely limit the ability of federal immigration authorities to release immigrants they detain. Venezuelan nationals Johan Jose Martinez-Rangel, 22, and Franklin Jose Peña Ramos, 26, have been charged with capital murder in the death of Jocelyn Nungaray, whose body was found in a creek June 17 after she disappeared during a walk to a convenience store. The two men entered the United States illegally earlier this year on separate occasions near El Paso. They were arrested by the U.S. Border Patrol but later released with orders to appear in court at a later date, according to the U.S. Department of Immigration and Customs Enforcement, or ICE. 🔎Source #US ☠️ Blood Meridian

Hashtags

123•••5•••10•••15•••20•••25•••30•••35•••40•••45•••50•••55•••60•••65•••70•••75•••7980
ПретходнаСтраница 1 од 80Следна