#РаботаСzip-архивами
Код из видео:
# Чтение архива
import zipfile
file_zip = zipfile.ZipFile("info.zip", "r")
for file_info in file_zip.infolist():
print(file_info.filename, file_info.date_time, file_info.file_size)
file_zip.close()
# Извлечение файлов из архива
import zipfile
file_zip = zipfile.ZipFile('info1.zip')
file_zip.extractall('./')
file_zip.close()
# Добавление файла в zip-архив
import zipfile
file_zip = zipfile.ZipFile('info.zip', 'w')
file_zip.write('info/inform.txt')
print('Файлы добавлены!')
file_zip.close()
# Добавление большего количества файлов с определённым расширением
import os
import zipfile
file_zip = zipfile.ZipFile('info_one.zip', 'w')
for folder, subfolders, files in os.walk('путь к папке с .txt файлами'):
for file in files:
if file.endswith('.txt'):
file_zip.write(os.path.join(folder, file),
os.path.relpath(os.path.join(folder, file), 'путь к папке с .py файлом'),
compress_type=zipfile.ZIP_DEFLATED)
file_zip.close()
# Проверка, является файл zip-архивом
import zipfile
test_files = ['zip.py', 'newInform.zip']
for file in test_files:
print('ZIP status for {0}: {1}'.format(file, zipfile.is_zipfile(file)))
Код из видео:
# Чтение архива
import zipfile
file_zip = zipfile.ZipFile("info.zip", "r")
for file_info in file_zip.infolist():
print(file_info.filename, file_info.date_time, file_info.file_size)
file_zip.close()
# Извлечение файлов из архива
import zipfile
file_zip = zipfile.ZipFile('info1.zip')
file_zip.extractall('./')
file_zip.close()
# Добавление файла в zip-архив
import zipfile
file_zip = zipfile.ZipFile('info.zip', 'w')
file_zip.write('info/inform.txt')
print('Файлы добавлены!')
file_zip.close()
# Добавление большего количества файлов с определённым расширением
import os
import zipfile
file_zip = zipfile.ZipFile('info_one.zip', 'w')
for folder, subfolders, files in os.walk('путь к папке с .txt файлами'):
for file in files:
if file.endswith('.txt'):
file_zip.write(os.path.join(folder, file),
os.path.relpath(os.path.join(folder, file), 'путь к папке с .py файлом'),
compress_type=zipfile.ZIP_DEFLATED)
file_zip.close()
# Проверка, является файл zip-архивом
import zipfile
test_files = ['zip.py', 'newInform.zip']
for file in test_files:
print('ZIP status for {0}: {1}'.format(file, zipfile.is_zipfile(file)))
#КонвертерВалют
Код из видео:
from currency_converter import CurrencyConverter
from tkinter import *
def exchange():
e_usd.delete(0, END)
e_eur.delete(0, END)
e_gbp.delete(0, END)
e_usd.insert(0, '%.2f' % c.convert(e_rub.get(), 'RUB', 'USD'))
e_eur.insert(0, '%.2f' % c.convert(e_rub.get(), 'RUB', 'EUR'))
e_gbp.insert(0, '%.2f' % c.convert(e_rub.get(), 'RUB', 'GBP'))
root = Tk()
root.title('Конвертер валют')
root.geometry('300x250+300+300')
root.resizable(width=False, height=False)
root['bg'] = 'black'
c = CurrencyConverter()
header_frame = Frame(root)
header_frame.pack(fill=X)
header_frame.grid_columnconfigure(0, weight=1)
header_frame.grid_columnconfigure(1, weight=1)
header_frame.grid_columnconfigure(2, weight=1)
h_currency = Label(header_frame, text='Валюта', bg='black', fg='lime', font='Arial 12 bold')
h_currency.grid(row=0, column=0, sticky=EW)
h_course = Label(header_frame, text='Курс', bg='black', fg='lime', font='Arial 12 bold')
h_course.grid(row=0, column=1, columnspan=2, sticky=EW)
# USD курс
usd_currency = Label(header_frame, text='USD', font='Arial 10')
usd_currency.grid(row=1, column=0, sticky=EW)
usd_one = Label(header_frame, text='1', font='Arial 10')
usd_one.grid(row=1, column=1, sticky=EW)
usd_converted = Label(header_frame, text='%.2f' % c.convert(1, 'USD', 'RUB'), font='Arial 10')
usd_converted.grid(row=1, column=2, sticky=EW)
# EUR курс
eur_currency = Label(header_frame, text='EUR', font='Arial 10')
eur_currency.grid(row=2, column=0, sticky=EW)
eur_one = Label(header_frame, text='1', font='Arial 10')
eur_one.grid(row=2, column=1, sticky=EW)
eur_converted = Label(header_frame, text='%.2f' % c.convert(1, 'EUR', 'RUB'), font='Arial 10')
eur_converted.grid(row=2, column=2, sticky=EW)
# GBP курс
gbp_currency = Label(header_frame, text='GPB', font='Arial 10')
gbp_currency.grid(row=3, column=0, sticky=EW)
gbp_one = Label(header_frame, text='1', font='Arial 10')
gbp_one.grid(row=3, column=1, sticky=EW)
gbp_converted = Label(header_frame, text='%.2f' % c.convert(1, 'GBP', 'RUB'), font='Arial 10')
gbp_converted.grid(row=3, column=2, sticky=EW)
calc_frame = Frame(root, bg='black')
calc_frame.pack(expand=1, fill=BOTH)
calc_frame.grid_columnconfigure(1, weight=1)
# RUB
l_rub = Label(calc_frame, text='Рубли: ', bg='black', fg='lime', font='Arial 12 bold')
l_rub.grid(row=0, column=0, padx=10)
e_rub = Entry(calc_frame, justify=CENTER, font='Arial 10')
e_rub.grid(row=0, column=1, columnspan=2, pady=10, padx=10, sticky=EW)
btn_calc = Button(calc_frame, text='Конвертировать', command=exchange)
btn_calc.grid(row=1, column=1, columnspan=2, sticky=EW, padx=10)
res_frame = Frame(root)
res_frame.pack(expand=1, fill=BOTH, pady=5)
res_frame.grid_columnconfigure(1, weight=1)
# USD
l_usd = Label(res_frame, text='USD', font='Arial 10 bold')
l_usd.grid(row=2, column=0)
e_usd = Entry(res_frame, justify=CENTER, font='Arial 10')
e_usd.grid(row=2, column=1, columnspan=2, padx=10, sticky=EW)
# EUR
l_eur = Label(res_frame, text='EUR', font='Arial 10 bold')
l_eur.grid(row=3, column=0)
e_eur = Entry(res_frame, justify=CENTER, font='Arial 10')
e_eur.grid(row=3, column=1, columnspan=2, padx=10, sticky=EW)
# GBP
l_gbp = Label(res_frame, text='GBP', font='Arial 10 bold')
l_gbp.grid(row=4, column=0)
e_gbp = Entry(res_frame, justify=CENTER, font='Arial 10')
e_gbp.grid(row=4, column=1, columnspan=2, padx=10, sticky=EW)
print(c.bounds['USD'])
root.mainloop()
Код из видео:
from currency_converter import CurrencyConverter
from tkinter import *
def exchange():
e_usd.delete(0, END)
e_eur.delete(0, END)
e_gbp.delete(0, END)
e_usd.insert(0, '%.2f' % c.convert(e_rub.get(), 'RUB', 'USD'))
e_eur.insert(0, '%.2f' % c.convert(e_rub.get(), 'RUB', 'EUR'))
e_gbp.insert(0, '%.2f' % c.convert(e_rub.get(), 'RUB', 'GBP'))
root = Tk()
root.title('Конвертер валют')
root.geometry('300x250+300+300')
root.resizable(width=False, height=False)
root['bg'] = 'black'
c = CurrencyConverter()
header_frame = Frame(root)
header_frame.pack(fill=X)
header_frame.grid_columnconfigure(0, weight=1)
header_frame.grid_columnconfigure(1, weight=1)
header_frame.grid_columnconfigure(2, weight=1)
h_currency = Label(header_frame, text='Валюта', bg='black', fg='lime', font='Arial 12 bold')
h_currency.grid(row=0, column=0, sticky=EW)
h_course = Label(header_frame, text='Курс', bg='black', fg='lime', font='Arial 12 bold')
h_course.grid(row=0, column=1, columnspan=2, sticky=EW)
# USD курс
usd_currency = Label(header_frame, text='USD', font='Arial 10')
usd_currency.grid(row=1, column=0, sticky=EW)
usd_one = Label(header_frame, text='1', font='Arial 10')
usd_one.grid(row=1, column=1, sticky=EW)
usd_converted = Label(header_frame, text='%.2f' % c.convert(1, 'USD', 'RUB'), font='Arial 10')
usd_converted.grid(row=1, column=2, sticky=EW)
# EUR курс
eur_currency = Label(header_frame, text='EUR', font='Arial 10')
eur_currency.grid(row=2, column=0, sticky=EW)
eur_one = Label(header_frame, text='1', font='Arial 10')
eur_one.grid(row=2, column=1, sticky=EW)
eur_converted = Label(header_frame, text='%.2f' % c.convert(1, 'EUR', 'RUB'), font='Arial 10')
eur_converted.grid(row=2, column=2, sticky=EW)
# GBP курс
gbp_currency = Label(header_frame, text='GPB', font='Arial 10')
gbp_currency.grid(row=3, column=0, sticky=EW)
gbp_one = Label(header_frame, text='1', font='Arial 10')
gbp_one.grid(row=3, column=1, sticky=EW)
gbp_converted = Label(header_frame, text='%.2f' % c.convert(1, 'GBP', 'RUB'), font='Arial 10')
gbp_converted.grid(row=3, column=2, sticky=EW)
calc_frame = Frame(root, bg='black')
calc_frame.pack(expand=1, fill=BOTH)
calc_frame.grid_columnconfigure(1, weight=1)
# RUB
l_rub = Label(calc_frame, text='Рубли: ', bg='black', fg='lime', font='Arial 12 bold')
l_rub.grid(row=0, column=0, padx=10)
e_rub = Entry(calc_frame, justify=CENTER, font='Arial 10')
e_rub.grid(row=0, column=1, columnspan=2, pady=10, padx=10, sticky=EW)
btn_calc = Button(calc_frame, text='Конвертировать', command=exchange)
btn_calc.grid(row=1, column=1, columnspan=2, sticky=EW, padx=10)
res_frame = Frame(root)
res_frame.pack(expand=1, fill=BOTH, pady=5)
res_frame.grid_columnconfigure(1, weight=1)
# USD
l_usd = Label(res_frame, text='USD', font='Arial 10 bold')
l_usd.grid(row=2, column=0)
e_usd = Entry(res_frame, justify=CENTER, font='Arial 10')
e_usd.grid(row=2, column=1, columnspan=2, padx=10, sticky=EW)
# EUR
l_eur = Label(res_frame, text='EUR', font='Arial 10 bold')
l_eur.grid(row=3, column=0)
e_eur = Entry(res_frame, justify=CENTER, font='Arial 10')
e_eur.grid(row=3, column=1, columnspan=2, padx=10, sticky=EW)
# GBP
l_gbp = Label(res_frame, text='GBP', font='Arial 10 bold')
l_gbp.grid(row=4, column=0)
e_gbp = Entry(res_frame, justify=CENTER, font='Arial 10')
e_gbp.grid(row=4, column=1, columnspan=2, padx=10, sticky=EW)
print(c.bounds['USD'])
root.mainloop()
elka.png
247.8 KB
#АнимированнаяОткрытка
Код из видео:
from tkinter import *
from PIL import ImageTk, Image
import random
root = Tk()
root.title('С Новым Годом!')
root.resizable(width=False, height=False)
cWidth = 1280
cHeight = 720
c = Canvas(root, width=cWidth, height=cHeight, bg='#002655')
c.pack()
image = ImageTk.PhotoImage(file='elka.png')
c.create_image(100, 100, image=image, anchor=NW)
def createText():
cText = ('''
Какая сказка за окном!
Кружат снежинки, будто в вальсе,
Весь мир пропитан волшебством,
И воздух переполнен счастьем.
Пусть в этот чудный Новый год
Удача в двери постучится,
И счастье вместе с ней войдет,
И все, что хочешь ты, случится!
''')
c.create_text(cWidth * 2 / 3, cHeight / 2, text=cText, fill='white', font='Times 24 bold')
def createSnow(t, n):
for i in range(500):
x = random.randint(1, cWidth)
y = random.randint(-cHeight * n - 8, cHeight * (1 - n))
w = random.randint(3, 8)
c.create_oval(x, y, x + w, y + w, fill='white', tag=t)
def motion():
Код из видео:
from tkinter import *
from PIL import ImageTk, Image
import random
root = Tk()
root.title('С Новым Годом!')
root.resizable(width=False, height=False)
cWidth = 1280
cHeight = 720
c = Canvas(root, width=cWidth, height=cHeight, bg='#002655')
c.pack()
image = ImageTk.PhotoImage(file='elka.png')
c.create_image(100, 100, image=image, anchor=NW)
def createText():
cText = ('''
Какая сказка за окном!
Кружат снежинки, будто в вальсе,
Весь мир пропитан волшебством,
И воздух переполнен счастьем.
Пусть в этот чудный Новый год
Удача в двери постучится,
И счастье вместе с ней войдет,
И все, что хочешь ты, случится!
''')
c.create_text(cWidth * 2 / 3, cHeight / 2, text=cText, fill='white', font='Times 24 bold')
def createSnow(t, n):
for i in range(500):
x = random.randint(1, cWidth)
y = random.randint(-cHeight * n - 8, cHeight * (1 - n))
w = random.randint(3, 8)
c.create_oval(x, y, x + w, y + w, fill='white', tag=t)
def motion():
👍6🎄1
#УведомленияWindows10
Код из видео:
from win10toast import ToastNotifier
toast = ToastNotifier()
# Добавление уведомления
toast.show_toast('Заголовок', 'Уведомление!', duration=10, icon_path='notepad.ico')
# Можно также сделать так, чтобы уведомления появлялись спустя определённое кол-во времени:
while True:
toast = ToastNotifier()
toast.show_toast('Заголовок', 'Уведомление!', duration=10)
time.sleep(5)
# Функция для создания уведомлений
def windows_popup(title, content, duration=10):
toast = ToastNotifier()
toast.show_toast(title, content, duration=duration, icon_path='notepad.ico')
windows_popup('Заголовок', 'Пора снимать видео!')
windows_popup('Заголовок2', 'Пора снимать второе видео!')
Код из видео:
from win10toast import ToastNotifier
toast = ToastNotifier()
# Добавление уведомления
toast.show_toast('Заголовок', 'Уведомление!', duration=10, icon_path='notepad.ico')
# Можно также сделать так, чтобы уведомления появлялись спустя определённое кол-во времени:
while True:
toast = ToastNotifier()
toast.show_toast('Заголовок', 'Уведомление!', duration=10)
time.sleep(5)
# Функция для создания уведомлений
def windows_popup(title, content, duration=10):
toast = ToastNotifier()
toast.show_toast(title, content, duration=duration, icon_path='notepad.ico')
windows_popup('Заголовок', 'Пора снимать видео!')
windows_popup('Заголовок2', 'Пора снимать второе видео!')
#ГенерацияСлучайныхСтрок
Код из видео:
import random
import string
# Сгенерируем 1 рандомный символ:
print(random.choices(string.ascii_lowercase))
print(''.join(random.choices(string.ascii_lowercase, k=5)))
# Случайная строка в верхнем регистре:
print(''.join(random.choices(string.ascii_uppercase, k=5)))
# Случайная строка в рандомном регистре:
print(''.join(random.choices(string.ascii_letters, k=5)))
# Так же строковые константы можно объединять:
print(''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase, k=5)))
Код из видео:
import random
import string
# Сгенерируем 1 рандомный символ:
print(random.choices(string.ascii_lowercase))
print(''.join(random.choices(string.ascii_lowercase, k=5)))
# Случайная строка в верхнем регистре:
print(''.join(random.choices(string.ascii_uppercase, k=5)))
# Случайная строка в рандомном регистре:
print(''.join(random.choices(string.ascii_letters, k=5)))
# Так же строковые константы можно объединять:
print(''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase, k=5)))
#СозданиеВиджетовНажатиемНаКнопку
Код из видео:
from tkinter import *
def click():
Button(root, text='Кнопка', font='Arial 15 bold', command=click2).pack()
Label(root, text='Какой-то текст').pack()
Entry(root, width=10).pack()
def click2():
Label(root, text='click').pack(expand=1, anchor=E)
Label(root, text='click').pack(expand=1, anchor=W)
root = Tk()
root.geometry('700x700')
root.title('Виждеты')
btn = Button(root, text='Создать виджет', font='Arial 15 bold', command=click)
btn.pack()
root.mainloop()
Код из видео:
from tkinter import *
def click():
Button(root, text='Кнопка', font='Arial 15 bold', command=click2).pack()
Label(root, text='Какой-то текст').pack()
Entry(root, width=10).pack()
def click2():
Label(root, text='click').pack(expand=1, anchor=E)
Label(root, text='click').pack(expand=1, anchor=W)
root = Tk()
root.geometry('700x700')
root.title('Виждеты')
btn = Button(root, text='Создать виджет', font='Arial 15 bold', command=click)
btn.pack()
root.mainloop()
#ИспользованиеProxyСерверовВPython
Код из видео:
import requests
proxies = {
'https': 'https://ip:порт'
}
data = requests.get('https://ipinfo.io/json', proxies=proxies)
print(data.text)
print(data.json()['city'])
Код из видео:
import requests
proxies = {
'https': 'https://ip:порт'
}
data = requests.get('https://ipinfo.io/json', proxies=proxies)
print(data.text)
print(data.json()['city'])
#ИзвлечениеИзображенийИзPDF
Код из видео:
import fitz
file = 'test.pdf'
pdf = fitz.open(file)
for i in range(len(pdf)):
for image in pdf.getPageImageList(i):
xref = image[0]
pix = fitz.Pixmap(pdf, xref)
if pix.n < 5:
pix.writePNG(f'{xref}.png')
else:
pix1 = fitz.open(fitz.csRGB, pix)
pix1.writePNG(f'{xref}.png')
pix1 = None
Код из видео:
import fitz
file = 'test.pdf'
pdf = fitz.open(file)
for i in range(len(pdf)):
for image in pdf.getPageImageList(i):
xref = image[0]
pix = fitz.Pixmap(pdf, xref)
if pix.n < 5:
pix.writePNG(f'{xref}.png')
else:
pix1 = fitz.open(fitz.csRGB, pix)
pix1.writePNG(f'{xref}.png')
pix1 = None
#ЧасыВbatФайле
Код из видео:
chcp 65001
@echo off
@title Часы
@mode con: cols=20 lines=4
color a
:path
echo ╔════════════════╗
echo ║ Время %time:~0,-3% ║
echo ╚════════════════╝
ping 127.0.0.1 -n 2 >nul
cls
goto:path
Код из видео:
chcp 65001
@echo off
@title Часы
@mode con: cols=20 lines=4
color a
:path
echo ╔════════════════╗
echo ║ Время %time:~0,-3% ║
echo ╚════════════════╝
ping 127.0.0.1 -n 2 >nul
cls
goto:path
#ДобавлениеДанныхВExcelТаблицу
Код из видео:
from openpyxl import load_workbook
fn = 'example.xlsx'
wb = load_workbook(fn)
ws = wb['data']
ws['A5'] = 'Привет, мир!'
wb.save(fn)
wb.close()
# Добавление строк целиком
ws.append(['Первый', 'Второй', 'Третий'])
ws.append(['Четвертый', 'Пятый', 'Шестой'])
ws.append(['Седьмой', 'Восьмой', 'Девятый'])
# Заполнение таблицы нажатием на кнопку
from openpyxl import load_workbook
from tkinter import *
from tkinter import messagebox
def save():
fn = 'example.xlsx'
wb = load_workbook(fn)
ws = wb['data']
data = (e.get(), lb['text'])
ws.append(data)
wb.save(fn)
wb.close()
messagebox.askokcancel('Сохранение', 'Успешно сохранено!')
root = Tk()
root.title('Тест')
root.geometry('200x200')
root.resizable(0, 0)
e = Entry(root)
e.pack()
lb = Label(root, text='1 лейбл', font='Arial 15 bold')
lb.pack()
btn = Button(root, text='Сохранить', font='Arial 15 bold', command=save)
btn.pack()
root.mainloop()
Код из видео:
from openpyxl import load_workbook
fn = 'example.xlsx'
wb = load_workbook(fn)
ws = wb['data']
ws['A5'] = 'Привет, мир!'
wb.save(fn)
wb.close()
# Добавление строк целиком
ws.append(['Первый', 'Второй', 'Третий'])
ws.append(['Четвертый', 'Пятый', 'Шестой'])
ws.append(['Седьмой', 'Восьмой', 'Девятый'])
# Заполнение таблицы нажатием на кнопку
from openpyxl import load_workbook
from tkinter import *
from tkinter import messagebox
def save():
fn = 'example.xlsx'
wb = load_workbook(fn)
ws = wb['data']
data = (e.get(), lb['text'])
ws.append(data)
wb.save(fn)
wb.close()
messagebox.askokcancel('Сохранение', 'Успешно сохранено!')
root = Tk()
root.title('Тест')
root.geometry('200x200')
root.resizable(0, 0)
e = Entry(root)
e.pack()
lb = Label(root, text='1 лейбл', font='Arial 15 bold')
lb.pack()
btn = Button(root, text='Сохранить', font='Arial 15 bold', command=save)
btn.pack()
root.mainloop()