day6

import os,datetime
dirs = ['tomcat','nginx','apache','python','app','android','ios']
os.chdir(r'E:\syz\ly-code\day6\logs')
base_path = r'E:\syz\ly-code\day6\logs'
for d in dirs:
p = os.path.join(base_path,d)
os.mkdir(p)
os.chdir(p)
for i in range(1,10):
t = datetime.date.today()+datetime.timedelta(-i)
name = '%s_%s.log'%(d,t)
open(name,'w')

def my_db(host,user,passwd,db,sql,port=3306,charset='utf8'):
import pymysql
coon = pymysql.connect(user=user,
host=host,
port=port,
passwd=passwd,
db=db,
charset=charset
)
cur = coon.cursor() #建立游标
cur.execute(sql)#执行sql
if sql.strip()[:6].upper()=='SELECT':
res = cur.fetchall()
else:
coon.commit()
res = 'ok'
cur.close()
coon.close()
return res
 

# Write something in the log of even-numbered dates.
# 1. Get all the files under the log directory os.walk()
# 2. Judging by the file name, whether it is an even date, split the string, and get the date
# 3, 12%2==0
# 4, Open this file open()
import os
for abs_path,dir,file in os.walk(r'E:\syz\ly-code\day6\logs'):
for f in file:
day = f.split('.' )[0].split('-')[-1]
if int(day)%2==0:
file_name = os.path.join(abs_path,f)#Splice absolute path
open(file_name,'a+', encoding='utf-8').write('write something')#


import sys 
import os
command = sys.argv
print(command)
if len(command)>1:
cmd1 = command[1]
if cmd1=='--help':
print('this is the help document'
'this python file is Used to illustrate the role of sys.argv')
elif cmd1=='os':
print('The current operating system is %s'%sys.platform)
else:
print('The input command is wrong')
else:
print(' When running python, you need to pass in a parameter'
'eg '
'python xx.py install ')
 
# import xpinyin 
# p = xpinyin. Pinyin() #Instantiation
# res = p. get_pinyin('Chen Weiliang','')
# print(res)

def say():
num1 = 1
num2 = 2
num3 = 3
return num1, num2,num3
res1,res2,res3 = say() #Anonymous

function, this function is very simple, only used once
# 1,33


import random
red_num = random.sample(range(1,34),6)
new_num = [ str (num).zfill(2) for num in red_num ] #List generation
l = [ i for i in range(1,101,2) ] #Generate odd numbers within 100, exchange space for time
#l2 = ( i for i in range(1,101,2) ) #Generate odd numbers within 100# #If there
are parentheses outside, it is not a list, it is a generator, #Generator
saves memory than list, it is every time it loops , will calculate an element according to the rules, put it in the memory
#list It is to put all the elements in the memory


for num in red_num:
tmp=str(num).zfill(2)
new_num.append(tmp) #Generator

,
# print(new_num)
# 1 3 5
a = 5
b = 4
# c = a if a > b else b # if a is greater than b, c=a, otherwise c = b , if you don't use the ternary operator, you have to write the following
if a > b:
c = a
else:
c = b

c = a if a > b else b #ternary expression

import 

xlwt book = xlwt.Workbook() #Create a new excel
sheet = book.add_sheet('sheet1')#Add sheet page
sheet.write(0,0,'Name')#Row, column, written content
sheet. write(0,1,'age')
sheet.write(0,2,'gender')
book.save('stu.xls')#The end must be .xls
import hashlib 


m = hashlib.md5()
# bytes
passwd = 'NHY_*&^_1982343532'
# passwd.encode() #Convert the string to bytes type
m.update(passwd.encode()) #Cannot direct string To encrypt, first convert the string to bytes type
print(m.hexdigest())
#md5 encryption is irreversible

#crash library
# befor after
# nhy123 81fb61ce98e508df8dbe8da07ad9acfc

def my_md5(str):
import hashlib
new_str = str.encode() #put Convert string to bytes type
# new_str = b'%s'%str # Convert string to bytes type
m = hashlib.md5() #Instantiate md5 object
m.update(new_str) #Encrypt
return m.hexdigest() #Get the result and return

# hashlib.sha512

d = {'a':8,'b':2,'c':3} 

#The dictionary is unordered, and there is no direct ordering of the dictionary.
print(d.items())
res = sorted(d.items(),key=lambda x:x[1])
#sort, loop call
# print(res)
# for k,v in res:
# print(k ,v)
l = [
[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[1,2 ,3,4]

]
# for a,b,c,d in l:
# print(d)

def my(name:str):
print(name)

import os #Some 
operations on the operating system
# print(os.getcwd())#Get the current working directory
# os.chmod("x.py",2)#Add permissions to files/directories, which is not good for Windows make
#1 execute
#2 write
#4 read
#
#chmod # print(os.chdir("../day5"))# change current directory
# print(os.getcwd())
#
# print(os.makedirs(" nhy/python"))#Create a folder recursively, create a parent directory when the parent directory does not exist
# print(os.mkdir("zll/huangrong"))#Create a folder#
makedirs When creating a folder, if the parent directory does not exist Existing will automatically create a parent directory for you
# print(os.removedirs("nhy/python"))#Recursively delete empty directories
# print(os.rmdir("test2"))#Delete the specified folder #Can
only delete empty directories Directory
# os.remove("test2")#Can only delete files
# os.rmdir('test2') #Can only delete folders


# print(os.listdir('e:\\'))#List a directory All files under

# os.rename("test","test1")#Rename
# print(os.stat("x.py"))#Get file information

print(os.sep)#The path separator of the current operating system#

# day5+os.sep+x.py
# print(os.linesep)#The newline character of the current operating system
# \n \r\n
# print(os .pathsep)#The separator of each path in the environment variable of the current system, linux is:, windows is;
# print(os.environ)#The environment variable of the current system
# print(os.name)#The name of the current system Windows system All are nt linux are all posix
# res = os.system('ipconfig') #Execute the operating system command, but can not get the result
#res = os.popen('ipconfig').read() #Can get the command Execution result
# __file__ #Get the absolute path to the current file
# print(os.path.abspath(__file__))#Get the absolute path
# print(os.path.split("/usr/hehe/hehe.txt")) #Split path and file name

# print(os.path.dirname("e:\\syz\\ly-code"))#Get the parent directory, get its parent directory
# print(os.path.basename( "e:\\syz\\ly-code\\a.txt"))#Get the last level, if it is a file, display the file name, if it is a directory, display the directory name
# print(os.path.exists(r"E :\syz\ly-code\day6"))#Does the directory/file exist?
# print(os.path.isabs("../day5"))#Determine whether it is an absolute path
# print(os.path.isfile("xiaohei.py")) #Determine
whether it is a file, 1. The file must be Exist 2. Must be a file
# print(os.path.isdir("e:\\syz1"))#Is it a path, whether the directory exists
size = os.path.getsize('x.py') #Get The size of the file
# cannot exceed 2m
# print(size)

# print(os.path.join("root",'hehe','mysql','a.sql'))#Spliced ​​into a path

# for abs_path,dir ,file in os.walk(r'E:\syz\ly-code\day6'): #Get the contents of the directory os.listdir()
# #
# print(abs_path,dir,file)
# abs_path The absolute path of the current loop
# All folders under the dir directory [ ]
# All files under the file directory []

#1, commonly used modules os, sys, time, datetime, hashlib
#2, how to import modules in other directories

#3, operate database
import sys
# print(sys.platform) #judgment operating system
# #python environment variables
# sys.path.append(r'E:\syz\ly-code\day5')
# sys.path.insert(0,r'E:\syz\ly-code\day5')
# print(sys.path )

# import nhy
# nhy.my()
# print(nhy.name)
# import nhy
# nhy.my()
# print(nhy.name)

print(sys.argv) #Used to get the python file running on the command line parameters passed in
 
import pymysql 
# 1, connect to database account, password ip port number database
#2, create cursor
#3, execute sql
#4, get result
# 5, close cursor
#6, close the connection
coon = pymysql.connect(
host='118.24 .3.40',user='jxz',passwd='123456',
port=3306,db='jxz',charset='utf8'
#port must write int type,
#charset must write utf8 here
)
cur = coon.cursor () #Create a cursor
# cur.execute('select * from stu;')#Execute sql statement
cur.execute('insert into stu (id,name,sex) VALUE (1,"Niu Hanyang","Female"); ')
# delete update insert
coon.commit() #must get coomit
res = cur.fetchall() #get all the returned results
print(res)
cur.close()#close the cursor
coon.close()#close the connection
 
import time 

#1, how many seconds have passed since the timestamp from the first year of unix
#2, the formatted time

# first convert to a time tuple

# print(time.time())
#get the current timestamp # time.sleep (10)
today = time.strftime('%Y%m%d%H%M%S')
# print(today)

# print(time.gmtime()) #The default time is the standard time zone
s=time .localtime(1514198608) #Get the time of the current time zone
# print(time.strftime('%Y-%m-%d %H:%M:%S',s)) #Timestamp
conversion time tuple
# 1. Convert timestamp to time tuple time.localtime()
# 2. Convert time tuple to formatted time
def timestamp_to_fomat(timestamp=None,format='%Y-%m-%d %H: %M:%S'):
#1. Returns the current formatted time by default
#2. If a timestamp is passed in, convert the timestamp to a formatted time and return
if timestamp:
time_tuple = time.localtime(timestamp )
res = time.strftime(format,time_tuple)
else:
res = time.strftime(format) #default takes the current time
return res

# 2018-4-21
# tp = time.strptime('2018-4-21','%Y-%m-%d') #put the format Convert the converted time into a time tuple
# print(time.mktime(tp)) #Convert the time tuple into a timestamp
def strToTimestamp(str=None,format='%Y%m%d%H%M% S'):
# 20180421165643 #Default
returns the current timestamp
if str: #If the time is passed
tp = time.strptime(str,format) #The formatted time is converted into a time tuple
res = time.mktime(tp )# Then convert to timestamp
else:
res = time.time() #The default is to take the current timestamp
return int(res)

import datetime
print(datetime.datetime.today()) #Get the current time, accurate to seconds
print( datetime.date.today()) #accurate to days
res = datetime.datetime.today()+datetime.timedelta(days=1,minutes=5,seconds=5,weeks=5)
print(res.strftime('%Y-%m-%d'))
 
Last week's review 
Function
1, simplify code
2, improve code reusability
def func(name,sex='male',*args,**kwargs): #formal parameter
today = '20180421'
retrun today

func(' Xiaohei ') #Actual parameter If
the return value is not written, return None
retrun
1. Return the result of the function processing
2. End the function
Constant:
all capital letters are used to define the
PORT
local variable
.
If you want to modify the global variable in the function, you must use it first global declaration
global name
built-in functions
len()
type()
id()
max()
dir(name)
sorted()
open()
round(1,11)
range(1,19) #[1,18]


Module
1. pip install xpinyin #pip The version above python3.4 comes with it
2.
xpinyin.tar.gz
python setup.py install
xpinyin.whl
pip install xpinyin.whl
Standard module
1. Python comes with import random, json, os
2. Third-party module
3. Python file function written by itself

returns multiple values:
1. If the function returns multiple values, it will put these values Put it in a tuple
2. If the function returns multiple values, it can also use multiple variables to receive


new_num = [ str(num).zfill(2) for num in red_num ] #List generation
l = [ i for i in range(1,101,2) ] #Generate odd numbers within 100, exchange space for time
#l2 = ( i for i in range(1,101,2) ) #Generate odd numbers within 100# #If there
are parentheses outside, it It is not a list, it is a generator,
#Generator saves memory than list, it calculates an element according to the rules every time it loops, and puts it in memory
#list It is a

lambda
anonymous function that puts all elements in memory
lambda x: x+1 #The function body after the colon is also the processing logic of the function, and the return value before the colon
Commonly used standard module
os module:
os .listdir('e:\\') #List all files and folders in the directory
os.remove() #Delete files
os.rename(old,new) #Rename
print(os.sep)#Current operating system The path separator #
# res = os.system('ipconfig') #Execute the operating system command, but can not get the result
#res = os.popen('ipconfig').read() #Can get the command execution Result
# print(os.path.abspath(__file__))#Get the absolute path
#print(os.path.dirname("e:\\syz\\ly-code"))#Get the parent directory, get its previous Level directory
# print(os.path.exists(r"E:\syz\ly-code\day6")) #Judging whether a file or directory exists
print(os.path.isfile("xiaohei.py"))
#Judging Whether it is a file, 1. The file must exist 2. It must be a file
print(os.path.isdir("e:\\syz1"))#Is it a path, whether the directory exists
size = os.path.getsize('x.py') #Get the size of the file
os.path.join ("root",'hehe','mysql','a.sql') #Splice path
for abs_path,dir,file in os.walk(r'e:\nhy'):
print(abs_path,dir,file)
# abs_path The absolute path of the current loop
# All folders under the dir directory [ ]
# All files under the file directory []

The order in which python imports modules:
1. Find the python file to be imported from the current directory
2. From python The essence of finding the sys.path import

module in the environment variable of the Both ways are the same as sys.argv












It is used to obtain the parameters passed in when running the python file in the command line. It is a list.
This list has one parameter by default, which is the current file name


job:
1. In the logs directory, some files are empty
1. Delete In the log directory, all empty files
2. Delete files 5 days ago.
2. Write code to implement, export the data in the stu table in my database to
excel . When registering with id username passwd inside , the password stored is the encrypted password username pwd cpwd, which are all required. The user cannot log in repeatedly . Login account password Print the current date after the login is successful.





























Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324895795&siteId=291194637