Let's add some last week's modules:
import os
print (os.path.abspath (‘.‘)) # take the absolute path
print (os.path.abspath (‘..‘)) # take the parent path
print (os.path.abspath (‘.. \\ day3’))
# print (os.getcwd ())
print (os.listdir (‘C: \\ Users \ WANG \\ PycharmProjects \\ untitled’))
os.chdir (‘C: \\ Users \ WANG \\ PycharmProjects \\ untitled \\ day3’) # Change the current working directory
print (os.getcwd ())
############################### ################### ################################
res1 = os.system (‘ipconfig’) # used to execute operating system commands
# Used to execute operating system commands, but can only help you execute them, no results can be obtained
# print (‘res result:‘, res1)
res2 = os.popen (‘ipconfig’). read () # command to execute the operating system
print ('res result:', res2)
datetime module
import datetime
print (datetime.date.today ()) # today's date, only date
print (datetime.datetime.today ()) # time of day, date and time
print (datetime.date.today () + datetime.timedelta (days = -10)) # take the date ten days ago, directly enter -10, the default corresponding parameter days
res = datetime.datetime.today () + datetime.timedelta (hours = -10, minutes = -20, seconds = -15)
print (res.date ()) # get date only
print (res.time ()) # only get the time
print (res.timestamp ()) # timestamp
print (res.strftime (‘% Y-% m% H:% M:% S‘)) # get the format time
map, filter module
# The loop helps you call the function
import os
import time
def makir (dir_name):
if not os.path.isdir (dir_name):
os.mkdir (dir_name)
return True
dir_names = [‘android’, ’ios’, ’tomcat’, ’java’, ’python’, ’php’, ’nginx’]
# res = map (makir, dir_names) # loop to help you call functions
# res = list (map (makir, dir_names))
# print (res) # generator, save memory
# 1. Is the loop calling the function for you?
# 2. Have you got the return value of the function?
################################################### ################################
def timestampToStr (timestamp = None, format = ‘% Y-% m-% d% H:% M:% S’):
if timestamp:
time_tuple = time.localtime (timestamp) # convert to time tuple
return time.strftime (format, time_tuple)
return time.strftime (format)
all_data = (timestampToStr (int (time.time ())-86400 * i) for i in range (10))
# print (all_data)
# for a in all_data:
# print (a)
# res = [‘‘] # list, use space for time
# all_data # Save space and increase CPU calculation time
nums1 = [str (i) .zfill (2) for i in range (10)] # list
nums2 = (str (i) .zfill (2) for i in range (10)) # generator
# print (nums2)
################################################### ################################
def my (num):
if num% 2 == 0:
return True
# Difference between filter and map
res1 = list (filter (my, range (10))) # filter, which filters out the data that the function processed is false
# Keep only the function returns true data
res2 = list (map (my, range (10))) # I will get you whatever you return
print (‘res1:‘, res1, ‘\ nres2:‘, res2)
random module
import random
print (random.random ()) # take random decimals less than 1
print (random.randint (1,10)) # specify a range, take a random integer
s = ‘abcdef’
print (random.choice (s)) # Choose one randomly, only one
print (random.sample (s, 3)) #N randomly selected, the returned is a list
print (random.uniform (1,10)) # specify a range, randomly take a decimal
Here are some modules that may be commonly used:
Database
First talk about the database:
# Traditional relational database
# mysql oracle sql server sqllie db2
# id name passwd cratetime sut
# score
# Data is stored on disk
# Use SQL statements to manipulate data
# There is a relationship between tables
# Non-relational database nosql
# {‘Name‘: ‘xxx’, ’‘}
# mongodb data stored on disk
# redis data is stored in memory
Let's talk about the mysql database first:
# 1, connect to the database IP account password port number database
# 2, execute sql
# 3. Get the result
import pymysql
# Connect to the database
coon = pymysql.connect (host = ‘XXX.XXX.XXX.XXX’,
user = ‘XXX’,
password = ‘123456’,
port = 3306,
db = ‘XXX’,
charset = ‘utf8’,
autocommit = True) # autocommit
cur = coon.cursor () # create cursor
################################################### ################################
sql1 = ‘select * from nhy where name =" wangjian ";’
cur.execute (sql1) # execute SQL statement, it just helps you execute SQL statement, it will not return data to you
print (cur.fetchall ()) # Get results
print (cur.fetchone ()) # get a result
print (cur.fetchmany (3)) # specify how many
################################################### ################################
sql2 = ‘insert into nhy (name, pwd) value (" wangjian "," 1234567 ");‘
cur.execute (sql2)
coon.commit () # commit
cur.execute (sql1)
print (cur.fetchall ())
cur.close () # cursor close
coon.close () # connection closed
After talking about the mysql library, let's talk about redis
import redis
# Connect redis
r = redis.Redis (host = ‘XXX.XXX.XXX.XXX’, port = 6379, password = ‘XXX’, db = XXX)
# Add delete change
########################################## Add & modify data ######### ###################################
r.set (‘wj_info’, ’age 18 sex man abcdefghi’, 50) # increase data (Key, value, valid duration (seconds))
# retrieve data
res = r.get (‘wj_info’)
print (res)
# b‘age 18 sex man abcdefghi ’
# b stands for bytes type # binary
print (res.decode ()) # encoding
###################################### delete data########## ##################################
r.delete (‘wj_info’) # delete the specified key
r.flushdb () # clear all keys in the current database
###################################### Query data########## ##################################
print (r.keys ()) # get all keys
print (r.keys (‘* info’)) # keys ending in info, support fuzzy matching
r.exists (‘wj_info’) # Determine if this key exists, return True, False
# ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ ★★
# hash hash key
# Hash type you understand as a dictionary nesting a dictionary
# select 10 redis select 8 in the command line is to switch to the db8 database
# Add delete change
########################################## Add & modify data ######### ###################################
r.hset (‘sessions_wj’, ‘ABC1’, ‘123456789abcdefgh’)
r.hset (‘sessions_wj’, ‘ABC2’, ‘123456789abcdefgh’)
r.hset (‘sessions_wj’, ‘ABC3’, ‘123456789abcdefgh’)
##################################### delete data########### ##################################
r.hdel (‘sessions_wj’, ‘ABC2’) # delete the specified small key
r.delete (‘sessions_wj’) # delete the big key directly
##################################### Query data########### ##################################
print (r.hget (‘sessions_wj‘, ‘ABC3’)) # Get the data in the specified small key
print (r.hgetall (‘sessions_wj‘)) # Get all the data in the hash type
r.expire (‘sessions_wj’, 600) # specify expiration time
print (r.ttl (‘sessions_wj‘)) # Use to see the key expiration time
print (r.type (‘sessions_wj‘)) # use the key type
Know how to get the results, so let ’s talk about it
# Convert {b‘kate ‘: b’lq‘} into {‘kate‘: ‘lq’}
# res = r.hgetall (‘sessions_wj’)
# print (res)
# a = ()
# for k, v in res.items ():
# a [k.decode ()] = v.decode ()
# print (a)
######################################### Another Way ######### ###################################
# for k, v in res.items ():
# res [k.decode ()] = res.pop (k) .decode () # can save memory because it deletes the original key
# # Delete the original bytes key, so that there is no extra bytes data in res
# print (res)
After talking about the database, then let's find out how to encrypt data by the way --- here introduces MD5 encryption
# md5 Encryption Encapsulation Function
def myMd5 (s):
s = str (s)
m = hashlib.md5 (s.encode ()) # must pass a bytes type
print (m.hexdigest ()) # Get the encrypted result
return m.hexdigest ()
How to export the data after querying the database? Let's introduce how to operate excel ~
import xlwt
book = xlwt.Workbook () # create excel
sheet = book.add_sheet (‘stu_info’) # add a sheet
sheet.write (0,0, ‘student number’) # rows, columns
sheet.write (0,1, ‘student name’) # rows, columns
sheet.write (0,2, ‘Grade’) # rows, columns
sheet.write (1,0, ‘1‘)
sheet.write (1,1, ‘Little Black’)
sheet.write (1,2, ‘88 .5 ‘)
book.save (‘stu.xls’) # Be sure to use xls
How to write a log after writing excel?
import nnlog
my_log = nnlog.Logger (‘a.log’, when = ‘S’, backCount = 5) # when parameter indicates that D-days, S-seconds ... can be written in units; the backCount parameter indicates that several log files can be saved
# debug, info, warning, error
# my_log.debug (‘This is the debug level’)
# my_log.info (‘info level’)
# my_log.warning (‘warning level’)
# my_log.error (‘error level’)
nnlog.Logger.words = ‘Hahahahaha’
So how to email this excel file to others?
import yagmail
# Account password email server recipient cc subject body attachment
username = ‘[email protected]’
passwd = ‘XXXXXXXXXXXXX’
mail = yagmail.SMTP (user = username, password = passwd, host = ‘smtp.163.com’) # Security protocol, smtp_ssl = Ture If it is a qq mailbox, you need to add this parameter
# Connected to mailbox
mail.send (to = [‘[email protected]‘],
cc = [‘[email protected]‘],
subject = ‘ha ha ha ha ha ha ha ha ha’, # email subject
contents = ‘ha ha ha ha ha ha ha ha ha’, # Email content
attachments = r ‘? C: \ Users \ WANG \ Desktop \ stu.xls’ # email attachments
)