9. Time module:
Import timeprint (Time.clock ()) #返回处理器时间, 3.3 started obsolete , changed to Time.process_time () to measure the processor time, Not including sleep time, unstable, print (time.altzone/3600) #返回与utc时间的时间差 on Mac, print in seconds (Time.asctime ()) # Returns the time format "fri aug 19 11:14:16 2016", T = time.localtime () t2 = Time.localtime (Time.time () +3600*3) #时间运算, current time plus 3 h print (t) print (T2) print (Time.localtime ()) #返回本地时间 The Struct time Object Format # print (Time.gmtime (Time.time () -800000)) #返回utc时间的struc时间对象格式print (t.tm_ Year,t.tm_mday) Print (Time.time ()) #时间戳, beginning 1970 to present time print (Time.time ()/(3600*24*365)) print (Time.gmtime ()) # UTC time Print (Time.asctime (Time.localtime ())) #返回时间格式 "fri aug 19 11:14:16 2016", Print ( Time.ctime ()) #返回Fri Aug 19 12:38:29 2016 format, #日期字符串 turn Timestamp string_2_struct = time.strptime ("2016/05/22", "%y/%m/%d") #将 Date string turn struct Time Object Format string_3_struct = time.strPtime ("2016-05-22 23:30:30", "%y-%m-%d %h:%m:%s") #将 Date string turn into struct time Object format print ( string_2_struct) print (string_3_struct) #struct_2_stamp = time.mktime (string_2_struct) # Turn the struct time object into timestamp struct_3_stamp = time.mktime (string_3_struct) #将struct时间对象转成时间戳print (struct_2_ Stamp) print ("Struct_3_stamp", Struct_3_stamp) #将时间戳转为字符串格式print (Time.gmtime (Time.time () -86640)) # convert UTC timestamp to struct_time format print (Time.localtime (Time.time () -86640)) #将local时间戳转换成struct_time格式print ( Time.strftime ("%y-%m-%d %h:%m:%s", Time.gmtime ()) ) convert #将utc struct_time format to the specified string format t2 = time.strptime ("2016-11-11 23:30:30", "%y-%m-%d %h:%m:%s") #字符串转struct时间对象格式print ("Time Object T2", T2) T3 = time.mktime (T2) #将struct时间对象转成时间戳print ("timestamp t3", T3) #t3_str1 = time.strftime ("%y %m %d %h:%m:%s ", T3) #时间戳转字符串print (" Timestamp to String ", Time.strftime ("%y-%m-%d %h:%m:%s ", Time.gmtime ())) # Time plus minus import datetimeprint ("datetime". Center (, '-') print (Datetime.datetime.now ()) #返回 2016-08-19 12:47:03.941925print ( Datetime.date.fromtimestamp (Time.time ()) ) # timestamp goes directly to the date format 2016-08-19print ( Datetime.datetime.now () ) print (Datetime.datetime.now () + datetime.timedelta (3)) #当前时间 + 3-Day print (Datetime.datetime.now () + datetime.timedelta ( -3)) #当前时间-3-Day print (Datetime.datetime.now () - datetime.timedelta (3)) #当前时间-3 days print (Datetime.datetime.now () + datetime.timedelta ( hours=3)) #当前时间 + 3-hour print (Datetime.datetime.now () + datetime.timedelta (minutes=30)) #当前时间 + 30 min C_time = datetime.datetime.now () print (C_time.replace (minute=23,hour=23,month=5,day=1,year= 2020)) #时间替换
10, module:
Import random,stringprint (Random.random ()) #随机生成的一个实数, it is in the range of [0,1) print (Random.randint ()) #随机生成整数n, 1<=n <=2print (Random.randrange) #随机生成整数n, 1<=n<2print (random.sample (' qweasdasf ', 3) #random. Sample ( sequence, k), a fragment of the specified length is randomly obtained from the specified sequence. The sample function does not modify the original sequence list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Slice = random.sample (list, 5) #从list中随机获取5个元素, as a fragment return print (slice) print (list) #原有序列并没有改变. Print (string.ascii_letters) print (string.digits) str = string.ascii_letters+string.digitsprint (". Join (Random.sample (str,6))) #随机取6位 # Generate random captcha:checkcode = ' For i in range (4): current = random.randrange (0,4) if current != i: &NBSP;&NBSP;&NBSP;&NBSP;TEMP&NBSP;=&NBSP;CHR (Random.randint (65,90)) else: temp = random.raNdint (0,9) checkcode += '%s '%tempprint (Checkcode)
11, module:
Import shutil#http://www.cnblogs.com/wupeiqi/articles/4963027.html# f1 = open ("Time_ module.py ") # f2 = open (" time_module_new.py "," W ") # shutil.copyfileobj (F1,F2) #将文件内容拷贝到另一个文件中 , can be partial content #shutil.copy (r "C:\Users\Administrator\PycharmProjects\s14\day1\userdata.txt", "test_copy") #拷贝文件和权限, Copy a file to a file or a directory, R is the meaning of preserving the original value of the string, which means that the symbol is not escaped #shutil.copy2 () #在copy上的基础上再复制文件最后访问时间与修改时间也复制过来了, something like cp –p #shutil. CopyFile () #拷贝文件, CopyFile (&NBSP;SRC,&NBSP;DST) is copied from source Src to DST. The premise is, of course, that the destination address has writable permissions. The exception information thrown is ioexception. if the current DST already exists, it will be overwritten # shutil.copytree (r "C:\Users\Administrator\PycharmProjects\ S14\day4 "," Day4_new ") #copytree (olddir,newdir,true/flase), copy olddir copies a copy of Newdir, if the 3rd parameter is True, the copy directory will keep the symbolic connection under the folder. If the 3rd parameter is false, a physical copy will be generated in the replicated directory instead of the symbolic Connection ## shutil.rmtree () #递归的去删除文件 # shutil.move (SRC,&NBSP;DST) #递归的去移动文件 #shutil. Make_archive (' Base_name ', format,...) #创建压缩包并返回文件路径, for example: Zip, tar# shutil.make_archive (r "C:\day4_copy", format= "Zip", root_dir=r "C:\Users\ AdminIstrator\pycharmprojects\s14\day4 ") #压缩解压: Import zipfile# zip_obj = zipfile. ZipFile (R "C:\day4_copy.zip", "a") # ' R ' means opening an existing read-only zip file, ' W ' means emptying and opening a write-only zip file, or creating a write-only zip file; ' A ' means opening a zip file and adding content. # zip_obj.write ("Test_copy") #将test_copy文件写进压缩文件 # zip_obj.close () # z = zipfile. ZipFile ("C:\day5_copy.zip", "R") #解压zip文档中的所有文件到当前目录 # z.extractall () # z.close () # import tarfile# all the files under the workspace, package a tar file, and provide a way to extract some of the files in the tar file into the specified directory # tar = tarfile.open (r "c \ Daytest_copy.zip "," W ") # tar.add (R" C:\Users\Administrator\PycharmProjects\s14\day4 ", Arcname=" Tetsname ") # tar.add (r "C:\day5_copy.zip")
12.Json and Pickle serialization:
#Json serialization of Import Jsoninfo = {"Name": "Jack", "age": 23}f = Open ("Test.text", "W") #print (Type (Json.dumps (info)), json.dum PS (info)) F.write (info)) #json. Dumps encode a Python object as a JSON string f.close ()
#Json deserialization import json# supports all languages, Python,java, etc., but Json can only be used for simple Python objects such as dictionaries, lists, and so on. The function can not (pickle) f = open ("Test.text", "r") data = Json.loads (F.read ()) #json. Loads decodes the encoded JSON string into a Python object print (data[" Age "])
#import jsonimport pickledef Sayhi (name): Print ("Hello:", name) info = {"Name": "Jack", "age": +, "func": sayhi}f = Open ("Test.text", "WB") #print (Type (Json.dumps (info)), Json.dumps (info)) #f. Write (Pickle.dumps (info)) #json. Dumps Python object encoded as JSON string Pickle.dump (info,f) #等同于f. Write (Pickle.dumps (info)) F.close ()
Import Pickle#pickle#pickle is for all Python objects, but is limited to Python,java pickledef Sayhi (name): Print ("Hello:", name) F = Open (" Test.text "," RB ") #data = Pickle.loads (F.read ()) #json. Loads decodes the encoded JSON string into a Python object data = Pickle.load (f) #等同于data = Pickle.loads (F.read ()) Print (data["func") Print (data["func"] ("Jack")
Import Jsoninfo = {"Name": "Jack", "age": 23}f = Open ("Test.text", "W") #print (Type (Json.dumps (info)), Json.dumps (info)) F.write (Json.dumps (info)) #json. Dumps encode Python objects as JSON strings info["age"]=21f.write (Json.dumps (info)) F.close ()
Import jsonf = open ("Test.text", "r") #data = Pickle.loads (F.read ()) #json. Loads decodes the encoded JSON string into a Python object data = Json.load ( f) #等同于data = Pickle.loads (F.read ()) print (data) #注: Dump multiple times, load error. Try to dump it once, load it once.
Import pickle#pickle for all Python objects, but is limited to Python,java pickledef Sayhi (name): Print ("Hello:", name) info = {"Name": "Jack "," age ": +," func ": sayhi}f = Open (" Test.text "," WB ") #print (Type (Json.dumps (info)), Json.dumps (info)) F.write ( Pickle.dumps (info)) #json. Dumps encodes a Python object into a JSON string f.close ()
Import Pickle#pickle#pickle is for all Python objects, but is limited to Python,java pickledef Sayhi (name): Print ("Hello:", name) F = Open (" Test.text "," RB ") data = Pickle.loads (F.read ()) #json. Loads decodes the encoded JSON string into a Python object print (data[" func ") Print (data[" Func "] (" Jack "))
13. XML Processing:
import xml.etree.elementtree as et# create XML document new_xml = et. Element ("NameList") #根节点name = et. Subelement (New_xml, "name", attrib={"enrolled": "Yes"}) #子节点age = et. subelement (Name, "Age", attrib={"checked": "No"}) Sex = et. subelement (name, "Sex") sex.text = ' Name2 = et '. Subelement (New_xml, "name", attrib={"enrolled": "No"}) Age = et. Subelement (name2, "age") age.text = ' Et = et. ElementTree (new_xml) #生成文档对象et. Write ("Test_new.xml", encoding= "Utf-8", Xml_declaration=true) Et.dump ( New_xml) #打印生成的格式
Import xml.etree.elementtree as ettree = et.parse ("Test.xml") #解析文件root = Tree.getroot () #获取到根节点print (Root.tag) #打印根节点标签 # Traverse XML document for child in root: Print (Child.tag, child.attrib) #child. Attrib Node properties for i in child: print (I.tag,i.attrib,i.text) #i. Text node literal # only traverse year node for node in root.iter (' year '): print (node.tag,node.text) #修改for node in root.iter (' year '): new_year = int (Node.text) + 1 node.text = str (new_year) node.set ("Updated", "Yes") # Update Property Tree.write ("Xmltest.xml") #删除nodefor country in root.findall (' Country '): Rank = int (Country.find (' rank '). Text) if rank > 50: root.remove (CounTry) tree.write (' Output.xml ')
14, configparser module:
Import configparserconfig = configparser. Configparser () config["DEFAULT"] = {' serveraliveinterval ': ', ' ' Compression ': ' yes ', ' CompressionLevel ': ' 9 '}config[' bitbucket.org '] = {} config[' bitbucket.org ' [' User '] = ' HG ' config[' topsecret.server.com '] = {}topsecret = config[' topsecret.server.com ']topsecret[' host port '] = ' 50022 ' # mutates the parsertopsecret[' ForwardX11 '] = ' no ' # same hereconfig[' DEFAULT ' [' ForwardX11 '] = ' yes ' with open (' Example.ini ', ' W ') as Configfile: config.write (ConfigFile)
Import Configparserconfig = Configparser. Configparser () config.read ("Example.ini") print (Config.sections ()) #读: Section_name = config.sections () [1]print ( config[section_name]["host port"]) #print (config.options (section_name)) #print (Config.items (section_name)) #print ( "2312:", Config.get (' bitbucket.org ', ' user ')) for i,v in Config[section_name].items (): Print (i,v) #删除: config.remove_ Option (Section_name, "forwardx11") config.write (Open ("Example_new", "W")) #修改: Config.set (section_name, "host Port", " ") Config.write (Open (" Example_new "," w "))
15,hashlib module:
Import HASHLIBM = Hashlib.md5 () m.update (b "Jack") print (M.hexdigest ()) m.update (b "Rose") print (M.hexdigest ()) m2 = HASHLIB.MD5 () m2.update (b "Jackrose") print (M2.hexdigest ()) Hash2 = hashlib.sha256 () hash2.update (b "Jackrose") print ( Hash2.hexdigest ()) Hash3 = hashlib.sha512 () hash3.update (b "Jackrose") print (Hash3.hexdigest ()) Import HMAC #hmac module, It internally creates key and content for us to process and then encrypt h = hmac.new (b "Jack", B "Rose") print (H.hexdigest ())
16, logging module:
import logginglogging.basicconfig (filename= ' Example.log ', level= logging.info, format= '% (asctime) s % (filename) s % (Lineno) d - % (levelname) s % (message) s ', datefmt= '%m/%d/%y %i:%m:%s %p ') #日志写到文件 #level=loggin.info, set the logging level to INFO, i.e., Only logs that are more than the log is info or higher than the info level will be logged to file #format= '% (asctime) s % (message) s ', datefmt= '%m/%d/%y %i:%m:%s %p ', log format plus time #livel level: debug<info<error<warning<criticallogging.warning ("User [alex" attempted wrong password more than 3 times ") logging.critical (" server Is down ") logging.info (" Test info ") logging.debug (" Test debug ") logging.error (" Test error ")
#多输出: Import logging#create loggerlogger = logging.getlogger (' Test-log ') logger.setLevel ( Logging. DEBUG) # create console handler and set level to debugch = Logging. Streamhandler () Ch.setlevel (logging. DEBUG) # create file handler and set level to warningfh = Logging. Filehandler ("Access.log") fh.setlevel (logging. WARNING) # create formatterformatter = logging. Formatter ('% (asctime) s - % (name) s - % (levelname) s - % (message) s ') # add formatter to ch and fhch.setformatter (Formatter) fh.setformatter (formatter) # add ch and fh to loggerlogger.addhandler (CH) logger.addhandler (FH) # ' application ' codelogger.debug (' Debug message ') logger.info (' Info message ') logger.warn (' Warn message ') Logger.error (' Error message ') logger.critical (' Critical message ')
#文件自动截断: Import loggingfrom logging Import Handlerslogger = Logging.getlogger ("Timelog.log") log_file = "Timelog.log" # FH = Handlers. Rotatingfilehandler (filename=log_file,maxbytes=10,backupcount=3,encoding= "Utf-8") FH = handlers. Timedrotatingfilehandler (filename=log_file,when= "S", interval=5,backupcount=3,encoding= "utf-8") formatter = Logging. Formatter ('% (asctime) s% (module) s:% (Lineno) d% (message) s ') Fh.setformatter (Formatter) logger.addhandler (FH) Import Timetime.sleep (2) logger.warning ("Test1") Time.sleep (2) logger.warning ("test12") Time.sleep (2) logger.warning (" Test13 ") logger.warning (" test14 ")
17. Re Regular expression:
See: http://www.cnblogs.com/alex3714/articles/5161349.html
Python Learning (DAY5)