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

Резултати

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

Пребарај: #carbonfiber

当前筛选 #carbonfiber清除筛选
Auto Life

@revheadcrypto · Post #551 · 07.10.2024 г., 07:18

🚗💥 Introducing the Manhart MHXM 900! 💥🚗 Get ready to experience the ultimate BMW XM upgrade! 🌟 🔧Power Boost: From a stock 748 hp and 1000 Nm to an astonishing 900 hp and 1200 Nm! 💪🔥 ⚙️Suspension Upgrade: Featuring H&R springs for enhanced handling! 🛠️ 🛞Stunning Wheels: Equipped with eye-catching 24-inch Manhart wheels! 😍 🌌Carbon Fiber Body Kit: Lightweight and aggressive styling that enhances performance! 🖤 🖌️Luxurious Interior: Finished in a sleek grey-orange scheme with leather, Alcantara, and carbon accents! ✨ #Manhart#MHXM900#BMW#Performance#Tuning#CarEnthusiast#LuxuryCars#CarbonFiber#Auto

Auto Life

@revheadcrypto · Post #140 · 20.07.2024 г., 18:39

🏎️ McLaren Artura gets a massive wing and body kit by Novitec Novitec has added a giant wing mounted on pylons, along with a body kit, redesigned bumpers, and a new engine cover, all made of carbon fiber. The exhaust system can be crafted from stainless steel or Inconel, with an option for a gold coating at extra cost. Not only does it enhance the engine's sound, but it also boosts its performance by an estimated 35 horsepower, according to the tuners. #McLarenArtura#Novitec#carbonfiber#exhaustsystem#tuning#horsepowerboost

Auto Life

@revheadcrypto · Post #387 · 25.08.2024 г., 23:56

🚗✨ Restomod Magic: BMW 8 Series Reimagined! ✨🚗 Check out this stunning restomod of the first-generation BMW 8 Series! 🏎️💨 🔧 Upgrades Include: - Carbon Fiber Panels: Lightweight and sleek! 🖤 - Powerful V10 Engine: Swapped from the BMW M5 (E60) and bored out to 5.8 liters! 💥 - Modern Interior Touches: Blending classic with contemporary! 🛋️ #BMW#Restomod#8Series#M5#CarEnthusiast#ClassicMeetsModern#CarbonFiber#V10Power#Auto🚘💫

Auto Life

@revheadcrypto · Post #607 · 27.10.2024 г., 09:53

🚗✨Brabus Transforms Mercedes-AMG SL into a 1000-HP Shooting Brake!🔥 The new body and aerodynamic features are crafted entirely from carbon fiber. The turbocharged V8 has been enlarged from 4.0 to 4.5 liters, and now, combined with an electric motor on the rear axle, the powertrain delivers a staggering 1000 HP and 1620 Nm of torque! 💪⚡ These bespoke three-door beauties will be built to order, tailored to individual specifications. Pricing is not publicly disclosed. 💎 #Brabus#MercedesAMG#ShootingBrake#1000HP#LuxuryCars#CarEnthusiasts#CustomCars#AutomotiveExcellence#CarbonFiber#Auto

Auto Life

@revheadcrypto · Post #337 · 18.08.2024 г., 18:07

🚗💨 Introducing the Acura Integra Type S with HRC Factory Tuning! 🔥✨ Get ready to be amazed by the incredible upgrades: 🔹 Aggressive Front Bumper with an enhanced splitter 🔹 Sleek Rear Bumper featuring a diffuser 🔹 Carbon Fiber Hood for that lightweight edge 🔹 Forged 19-inch Wheels wrapped in Pirelli P Zero Trofeo R tires 🔹 Stunning Carbon Fiber Wing on aluminum supports To lighten the load: 🔸 Carbon Fiber Rear Doors 🔸 Recaro Seats for ultimate comfort and support 🔸 Strut Brace replacing the rear bench for added rigidity And let’s not forget the performance upgrades: 🔹 Coilover Suspension for precision handling 🔹 Six-Piston Brembo Brakes up front for unmatched stopping power This beast is built for the track! 🏁💥 #AcuraIntegraTypeS#HRC#FactoryTuning#CarEnthusiast#Performance#CarbonFiber#Brembo#Pirelli#Auto

Auto Life

@revheadcrypto · Post #193 · 29.07.2024 г., 12:42

Just sold at auction! 🚗💰 This stunning Alfa Romeo 2000 GTV restomod with a carbon fiber body went for $220,000. 🤑 It took around four years to build this beauty, with everything from the chassis to the powertrain being completely overhauled. 🛠️ Italian specialists worked on the chassis and body, while the rest of the work was done in Canada. The upgraded 2.0 carbureted engine's exact output isn't specified, but the original Alfa Romeo 2000 GTV came with a 130-horsepower engine. 🏁 #AlfaRomeo#2000GTV#Restomod#CarbonFiber#Auction#ClassicCar#LuxuryCar#ItalianStyle🇮🇹