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

Резултати

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

Пребарај: #sirjimmy

当前筛选 #sirjimmy清除筛选
English With Natives*

@sirjimmy · Post #31411 · 18.02.2025 г., 05:57

🇬🇧Popular English Idioms to Sound Like a Native Speaker 💣 BLEW ME AWAY: ✍🏽when something blows you away, you’re extremely impressed by it 🔺The exhibition just blew me away. I’d never seen so many beautiful paintings before. ☁️ BLOW SMOKE: ✍🏽to exaggerate or say things that aren’t true to make you seem better/ more knowledgeable than in reality 🔺I’m not blowing smoke. I have honestly read War and Peace by Tolstoy. 🐺 CRY WOLF: ✍🏽to call for help when you don’t need it 🔺Do you think Peter is in trouble or is he just crying wolf? #sirjimmy #teamjimmy

English With Natives*

@sirjimmy · Post #30833 · 20.11.2023 г., 16:06

Show your true colours | show your true colors🎨 ⌨Meaning You show your true colours if you show what you're really like, or you reveal your true character. 🚦For example 👀Bob always acts like he's a strong, brave guy, but when the hurricane hit he showed his true colors. He was too scared to go check on old Mrs Flowers, our next-door neighbour. 👀The players showed their true colours when they came back from three goals down to win the match. #sirjimmy #teamjimmy

English With Natives*

@sirJimmy · Post #29479 · 17.09.2022 г., 07:51

🇬🇧Popular English Idioms to Sound Like a Native Speaker 💣 BLEW ME AWAY: ✍🏽when something blows you away, you’re extremely impressed by it 🔺The exhibition just blew me away. I’d never seen so many beautiful paintings before. ☁️ BLOW SMOKE: ✍🏽to exaggerate or say things that aren’t true to make you seem better/ more knowledgeable than in reality 🔺I’m not blowing smoke. I have honestly read War and Peace by Tolstoy. 🐺 CRY WOLF: ✍🏽to call for help when you don’t need it 🔺Do you think Peter is in trouble or is he just crying wolf? #sirjimmy #teamjimmy

English With Natives*

@sirJimmy · Post #29474 · 15.09.2022 г., 10:48

Show your true colours | show your true colors🎨 ⌨Meaning You show your true colours if you show what you're really like, or you reveal your true character. 🚦For example 👀Bob always acts like he's a strong, brave guy, but when the hurricane hit he showed his true colors. He was too scared to go check on old Mrs Flowers, our next-door neighbour. 👀The players showed their true colours when they came back from three goals down to win the match. #sirjimmy #teamjimmy

English With Natives*

@sirJimmy · Post #29540 · 11.10.2022 г., 07:04

♻️ Alternatives of 5 words to enrich your vocabulary 😔 Sad 😩 miserable; gloomy; devastated; distressed; down at heard; distraught; distressed; dispirited; sorrowful; downcast; feeling blue; desolate. 🤯 Big 🌏 massive; huge; giant; gigantic; enormous; large; colossal; immense; bulky; tremendous; hefty; sizable; extensive; great; substantial. 😳Shocked 😟taken aback; lost for words; flabbergasted; staggered; outraged; astonished; astounded; stunned; speechless; appalled. 🐭 Small 🐥tiny; petite; mini; miniature; microscopic; minuscule; compact; pocket-sized; cramped; puny; undersized; limited; meager; modest; minute; pint-sized. 😾 Angry 😡irate; enraged; touchy; cross; resentful; indignant; infuriated; wound-up; worked-up; seething; raging; heated; bitter; bad-tempered; offended; frustrated. Boost your vocabulary with our channel #vocabulary #sirjimmy #teamjimmy

English With Natives*

@sirjimmy · Post #31983 · 16.02.2026 г., 12:42

🌪️Negative Personality Idioms + Challenge 🎯 • 🗣️ A windbag – talks nonstop • 🧊 A wet blanket – ruins the vibe • 👀 A busybody / nosy parker – always in your business • 👍 A yes-person – agrees with everything • 😖 A pain in the neck – seriously annoying • 🤯 A scatterbrain – forgetful and unfocused • 👦 A mama’s boy – overly dependent • 👐 A pushover – too easy to control • 😈 A troublemaker – causes drama • 💼 A social climber – status obsessed • 🐢 A slowcoach – painfully slow • 🗣️💬 A gossip – spreads rumors • 🪨 A rolling stone – never settles • 🛋️ A lazybones – super lazy • 🎩 A stuffed shirt – too formal • 😴 A bore – boring person • 🧐 A snob – looks down on others • 🚪 A gatecrasher – uninvited guest • 🧠❌Narrow-minded – closed-off thinker • 💔Hard-hearted –cold and cruel • 🐖Pig-headed – stubborn AF • 🐇Hare-brained – reckless thinker 💥Challenge: Can you guess the idiom from the description? 🤔 1️⃣ Someone who ruins the fun at a party → ? 2️⃣ Someone who talks way too much → ? 3️⃣ Someone who is too easy to control → ? 💡 Tip: Try using one of these idioms in a sentence today! ✍️ #Idioms #TeamJimmy #SirJimmy

English With Natives*

@sirjimmy · Post #31136 · 18.07.2024 г., 21:44

Stop and smell the roses 🌺 Meaning: To relax; to take time out of one's busy schedule to enjoy or appreciate the beauty of life. Example: 🌹 Slow down. Stop and smell the roses now and then. #teamjimmy #sirjimmy #idioms

English With Natives*

@sirjimmy · Post #30997 · 07.03.2024 г., 14:51

❌ A fast shower 🚿 ✅ A quick shower ❌ Respond the door 🚪 ✅ Answer the door ❌ Strong rain 🌧 ✅ Heavy rain ❌ Celebrate a party 🎉 ✅ Throw a party ❌ Ask for a wish 🤞🏻 ✅ Make a wish ❌ Strong taste 😑 ✅ Big taste ❌ Lost the time ⏳ ✅ Waste time ❌ Nice dreams 🛌 ✅ Sweet dreams #sirjimmy #teamjimmy #idioms

English With Natives*

@sirJimmy · Post #30245 · 25.04.2023 г., 09:17

🤨English Idioms Describing Character And Personality😜 ✅1. Pain in the neck – an irritating, annoying person Ex. Sarah is such a pain in the neck these days. ✅2. A people person – an outgoing person who gets along with people really well and is a good listener Ex. Tom is enthusiastic and positive and he is a people person. ✅3. Party animal – someone who likes to attend parties often Ex. Are you going out again tonight? You are such a party animal. ✅4. Cheapskate – a mean person who doesn’t like spending money Ex. He was always a cheapskate even though he was earning $200,000 a year. ✅5. Happy camper – a person who is always happy and satisfied. We often use ‘happy camper’ in the negative. Ex. The apartment was much smaller than I expected, I was not a happy camper. ✅6. Nerd – someone who is very interested in science or technology, particularly in computers Ex. He spends all weekends at his laptop, he is such a nerd. ✅7. Life and soul of the party – someone who is energetic, and good fun during social occasions. Ex. It was a great night, Jim was life and soul of the party. ✅8. Dipstick – a person who seems to be stupid (very informal) Ex. I don’t know whether to laugh or be angry at his behaviour. What a complete dipstick! ✅9. Down-to-earth – someone who is practical and close to reality, who accepts other people as equals Ex. Despite his wealth, he was a down-to-earth man. He was very generous and had a kind heart. ✅10. Early bird – a person who wakes up, arrives to work, etc. before the usual time This expression comes from the English proverb “The early bird catches the worm”. Ex. My Mum is the early bird in our family, she gets up at 5 o’clock in the morning. ✅11. Larger than life – someone who is more exciting or interesting than other people Ex. All who knew him would agree that his personality was larger than life, he was a joy to be around. #Idioms #Teamjimmy #sirjimmy

123•••10•••20•••2829
ПретходнаСтраница 1 од 29Следна