Python 语法总结

一、通过SMTP发送邮件

参考:

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import smtplib
import datetime
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

nt = datetime.datetime.now()
last7date=(nt - datetime.timedelta(days=7)).date()

def sendEmail(attachfilename):
    sender = 'curiouser@163.com'
    # 接收者邮件地址
    receivers = ['curiouser@qq.com','curiouser@163.com']

    message = MIMEMultipart()
    message['From'] = Header("robots@163", 'utf-8')
    message['To'] = Header('; '.join(str(e) for e in receivers)+'; ', 'utf-8')
    # 邮件主题内容
    message['Subject'] = Header(nt.strftime('%Y%m%d%H')+"Python测试SMTP发送邮件", 'utf-8')
    # 邮件正文内容
    message.attach(MIMEText("Python测试SMTP发送邮件,详情见附件Excel文件", 'plain', 'utf-8'))

    # 附件内容
    attachment = MIMEBase('application', "octet-stream")
    attachment.set_payload(open(attachfilename, "rb").read())
    encoders.encode_base64(attachment)
    attachment.add_header('Content-Disposition', 'attachment; filename="附件文件名"')
    message.attach(attachment)

    try:
        smtpObj = smtplib.SMTP('smtp.163.com')
        smtpObj.login("curiouser@163.com", "*********")
        smtpObj.sendmail(sender, receivers, message.as_string())
        print("邮件发送成功")
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")

def main():
  sendEmail("/tmp/test-email-attachfile.txt")

if __name__ == "__main__":
    main()

二、写入EXCEL

参考:https://blog.csdn.net/u013250071/article/details/81911434

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import xlwt
def createExcel(data,filename):
    # 创建excel工作表
    workbook = xlwt.Workbook(encoding='utf-8')
    # 给表格新建一个名为 sheer1 的工作簿
    worksheet = workbook.add_sheet('sheet1')

    # 创建一个样式对象,初始化样式
    style = xlwt.XFStyle()
    al = xlwt.Alignment()
    # 其中horz代表水平对齐方式,vert代表垂直对齐方式
    # VERT_TOP          = 0x00    上端对齐
    # VERT_CENTER    = 0x01    居中对齐(垂直方向上)
    # VERT_BOTTOM  = 0x02    低端对齐
    # HORZ_LEFT        = 0x01    左端对齐
    # HORZ_CENTER   = 0x02    居中对齐(水平方向上)
    # HORZ_RIGHT     = 0x03    右端对齐
    # style.alignment = al

    # 设置表头
    worksheet.write(0, 0, label='id')
    worksheet.write(0, 1, label='用户名')
    worksheet.write(0, 2, label='性别')
    worksheet.write(0, 3, label='年龄')
    worksheet.write(0, 4, label='学历')
    ordered_list = ["id", "用户名", "性别", "年龄", "学历"]
    row = 1
    for player in data:
        for _key, _value in player.items():
            col = ordered_list.index(_key)
            worksheet.write(row, col, _value, style)
        row += 1
    workbook.save(filename)

def main():
    testdata=[
        {'id': '1', '用户名': "test1", '性别': "男", '年龄': 18,'学历': "大学本科"},
        {'id': '2', '用户名': "test2", '性别': "男", '年龄': 25,'学历': "大学本科"}
    ]
    createExcel(testdata,"test.xls")

if __name__ == "__main__":
    main()

三、遍历字典列表

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
def main():
    testdata=[
        {'id': '1', '用户名': "test1", '性别': "男", '年龄': 18,'学历': "大学本科"},
        {'id': '2', '用户名': "test2", '性别': "男", '年龄': 25,'学历': "大学本科"}
    ]
    row = 1
    for i in testdata:
        for _key,_value in i.items():
            print(_key,"=",_value)
        row += 1

if __name__ == "__main__":
    main()

四、列表的遍历与拼接

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

def main():
    test_list = ['hello','world','I\'m','Python']
    print(' '.join(str(e) for e in test_list) + '!')
if __name__ == "__main__":
    main()

# 输出
hello world I'm Python!
Copyright Curiouser all right reserved,powered by Gitbook该文件最后修改时间: 2022-09-22 13:26:16

results matching ""

    No results matching ""