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

Резултати

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

Пребарај: #sentinels

当前筛选 #sentinels清除筛选
NewUU Student Council

@newuu_sc · Post #671 · 23.06.2023 г., 11:35

📢 Election Update: Renaissance Team Emerges Victorious!🎉 We are thrilled to announce the conclusion of the Student Council elections, held online through Google Forms from June 20 to 22. After an intense battle for leadership, the results are finally in! ✨ Team Renaissance has emerged as the winner, securing an impressive 59.3% of the votes! 🎊 We extend our warmest congratulations to their members for their outstanding campaign and commitment to making a positive impact on our school community. 🏅 We also commend the Sentinels team for their dedication and hard work, as they garnered a respectable 40.7% of the votes. Your participation and contributions have been invaluable throughout this process. We would like to express our gratitude to all candidates who put themselves forward for the Student Council elections. Your passion, ideas, and willingness to serve are truly commendable. A special thanks goes out to every student who participated in the voting process. Your engagement and enthusiasm have played a crucial role in shaping the future of our Student Council and the initiatives it will undertake. Let us now join hands and offer our full support to the Renaissance Team as they embark on their journey of leadership. Together, we can strive to create an inclusive and vibrant school environment that fosters growth, innovation, and collaboration. Best Regards, Student Affairs. 🎓🌟#StudentCouncilElections#Renaissance#Sentinels#Congratulations

NewUU Student Council

@newuu_sc · Post #639 · 14.06.2023 г., 09:06

📢 Attention all students of New Uzbekistan University! 🎓 The highly anticipated debates between the two candidates vying for the position of President of the Student Council will take place in the university Conference Hall. 🎙🏛 Join us for an engaging discussion as these candidates present their visions, plans, and goals for the next academic year. It's an excellent opportunity to get to know the potential leaders who will shape our university's future! 🌟✨ Whether you're passionate about academic improvements, extracurricular activities, or enhancing student welfare, this debate is the perfect platform to hear the candidates' perspectives and evaluate their abilities to meet our diverse needs. 📚🎉 Spread the word and see you all there! 🎉🗣 Date: June 16 Time: 16:00 Location: Conference hall #NewUzbekistanUniversity#StudentCouncilElections#Debate2023#Renaissance#Sentinels