Python學(xué)習(xí)筆記-第五天

** send mail**
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import smtplib
from email.mime.text import MIMEText
_user = "594017622@qq.com"
_pwd = "你的授權(quán)碼"
_to = "1210945390@qq.com"

msg = MIMEText("Test")
msg["Subject"] = "don't panic"
msg["From"] = _user
msg["To"] = _to

try:
    s = smtplib.SMTP_SSL("smtp.qq.com", 465)
    s.login(_user, _pwd)
    s.sendmail(_user, _to, msg.as_string())
    s.quit()
    print "Success!"
except smtplib.SMTPException, e:
    print "Falied,%s" % e
** database **
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb as mysqldb

# 打開數(shù)據(jù)庫連接
db = mysqldb.connect(host='localhost', user='root', passwd='root',
                     db='test')

# 使用cursor()方法獲取操作游標(biāo)
cursor = db.cursor()

# 使用execute方法執(zhí)行SQL語句
cursor.execute("SELECT * from test")

# 使用 fetchone() 方法獲取一條數(shù)據(jù)庫。
one_data = cursor.fetchone()
print one_data
data = cursor.fetchall()
print data

# 關(guān)閉數(shù)據(jù)庫連接
db.close()
** json **
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json

# json.dumps    將 Python 對(duì)象編碼成 JSON 字符串
# json.loads    將已編碼的 JSON 字符串解碼為 Python 對(duì)象

# json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
# allow_nan=True, cls=None, indent=None, separators=None,
# encoding="utf-8", default=None, sort_keys=False, **kw)
data = {'name': 'chenwenbo', 'age': 10}
json.dumps(data)
** file **
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs

# 打開文件
f = open('/Users/apple/code/python/io/demo.txt', 'r')
str = f.read()
# 關(guān)閉文件,避免占用資源
f.close()


# 更優(yōu)雅的寫法,使用完后自動(dòng)釋放資源
with open('/Users/apple/code/python/io/demo.txt', 'r') as f:
    print f.read()

with open('/Users/apple/code/python/io/demo.txt', 'r') as f:
    # 一行一行讀
    for line in f.readlines():
        # strip 去掉末尾的 \n
        print line.strip()

# 讀取圖片
# with open('/Users/apple/code/python/io/aaa.jpg', 'rb') as f:
    # print f.read()

# 如果讀取非unicode類型的文件,需要先以二進(jìn)制的形式讀取后,再轉(zhuǎn)碼
# with open('/Users/apple/code/python/io/aaa.txt', 'rb') as f:
    # print f.read().decode('gbk')
# 或者利用codecs模塊處理
# with codecs.open('/Users/apple/code/python/io/aaa.txt', 'r', 'gbk') as f:
    # print f.read()

# 寫文件 覆蓋
with open('/Users/apple/code/python/io/demo01.txt', 'w') as f:
    f.write('chen')
# 寫文件 追加
with open('/Users/apple/code/python/io/demo01.txt', 'a') as f:
    f.write('wen bo')
** dir **
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os

print os.name
print os.uname()

# 當(dāng)前目錄絕對(duì)路徑
print os.path.abspath('.')
# 在某個(gè)目錄下創(chuàng)建新目錄 join拼接可以避免不同操作系統(tǒng)的路徑表示
new_dir = os.path.join('/Users/apple/code/python/io/', 'test')
os.mkdir(new_dir)
os.rmdir(new_dir)

# 拆分目錄和文件
print os.path.split('/Users/apple/code/python/io/demo.txt')

# 拆分文件和拓展名
print os.path.splitext('/Users/apple/code/python/io/demo.txt')

# 文件重命名
# os.rename('/Users/apple/code/python/io/demo.txt',
#   'demo11.txt')

# 復(fù)制文件,os中沒有提供, shutil模塊提供了copyfile()函數(shù)可以進(jìn)行處理

# 列出當(dāng)前目錄下所有目錄
print [x for x in os.listdir('.') if os.path.isdir(x)]

# 列出當(dāng)前目錄下所有py文件
print [x for x in os.listdir('.') if os.path.splitext(x)[1] == '.py']

# Python的os模塊封裝了操作系統(tǒng)的目錄和文件操作,要注意這些函數(shù)有的在os模塊中,有的在os.path模塊中。
** 微信機(jī)器人 **
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import itchat
import requests
import json


# 圖靈機(jī)器人
def talks_robot(info='你叫什么名字'):
    api_url = 'http://www.tuling123.com/openapi/api'
    apikey = 'apikey'
    data = {'key': apikey,
            'info': info}
    req = requests.post(api_url, data=data).text
    replys = json.loads(req)['text']
    return replys


@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
    return talks_robot(msg['Text'])

itchat.auto_login()
itchat.run()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容