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

Резултати

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

Пребарај: #milestone

当前筛选 #milestone清除筛选
Viral Today

@Viral_Today · Post #1758 · 23.01.2022 г., 13:00

🎉Thank you for 10.000 followers! Thank you all for commenting, reacting and sharing our posts. It is always great to hear back from you! You can always suggest a post or contact us through our bot @ChannelYTNBot Stay tuned for more content! YouTubeNews/ #milestone

Hashtags

Venezuelanalysis

@venanalysis · Post #1461 · 28.01.2024 г., 14:43

A blend of US aggression and Venezuelan opposition collusion has all but sealed CITGO's destiny. Discover how Washington and its local allies successfully acquired Venezuela's US-based refiner, valued at US $10-13 billion, by clicking here 👉🏽https://bit.ly/3OkSfn8. View and download the infographic in a single image. Don't miss out on these insights! #CITGO#Infographic#milestone

SingSing Announcement

@singsingchannel · Post #680 · 08.07.2024 г., 04:06

🚀 We did it! Our community keeps growing stronger with over 90K Followers on X and more than 1 million on-chain transactions! 🚀💫 🎉 The numbers are still climbing, and we couldn't be more grateful for your support. Together, we'll keep reaching new heights! 💪🔥 Read more and open treasure at: X Post #Milestone#CommunityPower#Blockchain#Crypto

SingSing Announcement

@singsingchannel · Post #692 · 11.07.2024 г., 08:59

🎉 Milestone Alert! 🎉 SingSing has officially surpassed 1.2 MILLION on-chain transactions! 🚀 Thank you to our incredible community for making this possible. Here’s to many more milestones ahead! 💪✨ Read more and open treasure at: X Post #SingSing#Blockchain#Milestone#OnChain#CryptoCommunity

SingSing Announcement

@singsingchannel · Post #752 · 06.08.2024 г., 08:19

New Milestone🚀🚀 We've just hit the milestone of 500,000 Web3 users utilizing SingSing SocialFi SDK! 🎉🚀 Thank you for your support and participation. This achievement showcases the strength and potential of the SingSing community! 💪✨ Keep exploring and enjoying the super cool features of SingSing! 💎🔥 #SingSing#Web3#SocialFi#Milestone#SDK

Venezuelanalysis

@venanalysis · Post #1751 · 20.09.2024 г., 23:39

When discussing historic speeches, one stands out: President Hugo Chávez at the UN General Assembly on September 20, 2006. He labeled U.S. President George W. Bush a war criminal and highlighted Western hypocrisy regarding democracy and peace—right from “the devil’s house.” Chávez criticized the UN for its alignment with U.S. interests and called for reform led by the Global South. He underscored the ongoing struggle for change and the potential for a better future. Click here to learn more and watch the key quotes 👉🏼https://shorturl.at/guOJh #Milestone#HugoChávez#UN#Revolution

TMONK Announcements

@tmonkannouncements · Post #28 · 25.03.2024 г., 22:54

💎TMONK as you know, was born to spread the word of Telegram and its founder Durov. We said that we want to become the first #crowdfunding and #charity platform and we are working on both fronts. And so we are really proud to present the first AMBASSADOR on the #TONBlockchain regarding the charity sector. A person of absolute morality and great devotion to the cause. That who has already given part of his life to helping people in the field and who knows the ton chain deeply 👀👀👀Jeribond.ton🆒🆒🆒 Our Ambassador brings with a wealth of experiences and knowledge that make him an outstanding choice to represent TMONK. We are honored to have his leadership and inspiration to guide others on our journey. This is the first step to build the foundation of a structure that can be the #milestone in this theme for ton chain 🤝 About Jeribond.ton🤝 After working in the humanitarian sector for 8 years, Jeribond.ton has just resigned and is focusing on Web3. Jeribond.ton worked in the neonatal and maternal health sector for this while, because over here women face a lot of pregnancy complications and also newborn babies pre or post. So JERI worked in the community by training the health workers, doctors, and nurses to best carry out their duties using best practices that work in other countries, and this helped to reduce the rate of how women die. Jeribond.ton was instrumental as he managed the supplies and supported the work in many ways; with a small team obtained funding from an international organization to carry out these projects. BioCM - $TON$BNX - BD lead & Advisor @Tonraffles - @Roolznft $Fish OG @binaryniglions@https://t.me/tonnigeria @https://t.me/TonNomadsChat This is a crucial step for the advancements of our project, and we are truly proud to announce this new and exciting collaboration. We aim to build something new, something incredible that can help all the people in need around the world. FOR THEIR #FREEDOM

SingSing Announcement

@singsingchannel · Post #894 · 13.10.2024 г., 16:43

🎉100,000 Players and Counting!🎉 A huge THANK YOU to our incredible community for making SingSing Tycoon such a massive hit! 💥 Your support has helped us reach this amazing milestone, and we couldn’t have done it without you. 🙌 Here’s to many more tycoon adventures ahead! 🏗️💰 #SingSingTycoon#100KPlayers#Milestone#ThankYou#GameFi 🎤Announcement | Chat | X (Twitter) | Website | Game

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