Basic Python Learning 04

Source: Internet
Author: User
Tags create directory hmac local time sha1 timedelta

Module definition:to logically organize python.CodeVariable,Function,Class,Logic,The essence is. pyEnd of PythonFile,Implement a feature
Package Definition:Used to logically organize the module's,The essence is a directory,Must be with __init__.pyFile
Import:Import module_name1, module_name2From Package_nameor module_nameImport *
From Package_nameor module_nameImport funcAs Func_name
ImportModule Nature:The essence of the import module is to put PythonDocument explained once again
ImportPackage Essence:The essence of the import package is to execute the __init__.py under the packageFile
ImportHour,Can be in __init__.pyIn the file,Import the modules within the package (From.Import module_name),Such,When you import a package,The other modules under the package can be called
Categories of modules:
1)Standard library
2)Open source Module
3)Custom Modules


#Time ModuleTimeAndDatetime
Import time

#From1970-01-01 00:00:00Time stamp to current number of seconds
Print (Time.time ())
#Local time structured time can pass timestamp
Print (Time.localtime ())
#Dormancy
Time.sleep (1)
#Converts a timestamp intoUtcStructured time for Standard Time
Print (Time.gmtime (Time.time ()))
#Convert a structured time into a timestamp
Print (Time.mktime (Time.localtime ()))
#Convert structured time to string
Print (Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ()))
#Convert a string into structured time
Print (Time.strptime (' 2016-08-20 14:31:52 ','%y-%m-%d%h:%m:%s '))
#Convert structured time to English string,can receive tuples
Print (Time.asctime ())
#Convert structured time to English string,Time stamp can be received
Print (Time.ctime ())


Import datetime

#Get current time
Print (Datetime.datetime.now ())
#Time Calculation,Cannot be used alone
Print (Datetime.datetime.now () +datetime.timedelta (-3))
Print (Datetime.datetime.now () +datetime.timedelta (hours=-3))


#Random module
Import Random

#Random0-1Floating point number
Print (Random.random ())
#Random1-3Integer
Print (Random.randint (1,3))
#Random0-2Integer
Print (Random.randrange (1,3))
#Randomly taking values in sequence types
Print (Random.choice (' Hello '))
Print (Random.choice ([1,2,3,4]))
#Randomly taking in sequence types2-bit
Print (Random.sample (' Hello ',2))
#Floating point number in random interval
Print (Random.uniform (2,3))
#Randomly disrupt a sequence table
i = [1,2,3,4]
Random.shuffle (i)
Print (i)


OsModule

#Get current directory
Print (OS.GETCWD ())
#Switch directories
Os.chdir ("/Home")
Print (OS.GETCWD ())
#Return to current directory
Print (Os.curdir)
#Return to the top level directory
Print (Os.pardir)
#Recursively create directory Os.makedirs (Os.path.dirname (Os.path.abspath (__file__) + "/a/b/c") # Recursive Delete directory if directory is empty, then delete, and recursively to the previous level directory, if also empty, then delete, And so on Os.removedirs (Os.path.dirname (Os.path.abspath (__file__) + "/a/b/c") # Create Directory Os.mkdir (Os.path.dirname ( Os.path.abspath (__file__)) + "/a") # Delete empty directory Os.rmdir (Os.path.dirname (Os.path.abspath (__file__)) + "/A") # Display directory contents print ( Os.listdir (".")) # rename Os.rename (Os.path.dirname (Os.path.abspath (__file__)) + "/A", Os.path.dirname (Os.path.abspath (__file__)) + "/b") # Get File information print (Os.stat ("b/123")) # Output operating system-specific path delimiter print (OS.SEP) # Output current operating system newline character print (os.linesep) # Output string that separates the file path print ( OS.PATHSEP) # OUTPUT environment variable print (os.environ) # Output current system platform print (OS.NAME) # Execute system command Os.system ("dir") # Gets the absolute path of the current file print ( Os.path.abspath (__file__) # divides path into directory and file name print (Os.path.split (Os.path.dirname (os.path.abspath) + __file__) ") # Returns the directory of Path print (Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__) +"/b/123 ")) # returns the file name in the path directory print ( Os.path.basename (Os.path.dirname (Os.path.abspath (__file__)) + "/b/123") # Determine if the path exists print (Os.path.exisTS (Os.path.dirname (Os.path.abspath (__file__)) + "/b/123")) # determines if the absolute path print (Os.path.isabs ("Home")) # Determines whether the file is print ( Os.path.isfile ("b/123") # Combines multiple paths and returns the parameters before the first absolute path will be ignored by print (Os.path.join ('/home ', ' A.txt ')) # Gets the last access time of a file or directory print ( Os.path.getatime (Os.path.dirname (Os.path.abspath (__file__))) # Gets the last modified time for a file or directory print (Os.path.getatime ( Os.path.dirname (Os.path.abspath (__file__))) Shutil module http://www.cnblogs.com/wupeiqi/articles/4963027.html# Copy the contents of the file to another file, can be part of the content F1 = open (' 123 ', encoding= ' utf-8 ') F2 = open (' 1234 ', ' W ', encoding= ' Utf-8 ') shutil.copyfileobj (F1, F2) # Copy file Shutil.copyfile (' 123 ', ' 1234 ') # Copy only permissions. Content, group, user unchanged Shutil.copymode (' 123 ', ' 1234 ') # Copy status information, including: Mode Bits,atime, Mtime,falgsshutil.copystat (' 123 ', ' 1234 ') # Copy files and Permissions shutil.copy (' 123 ', ' 12345 ') # Copy files and status information Shutil.copy2 (' 123 ', ' 123456 ') # recursively de-copying Files Shutil.copytree (Os.path.dirname (Os.path.abspath (__file__)), Os.path.dirname (Os.path.dirname ( Os.path.abspath (__file__)) + "/New module") # Recursively delete directory Shutil.rmtree (Os.path.dirname (Os.path.dirname (Os.path.abspath __)))+"/New module") # Recursive Move file Shutil.copytree (Os.path.dirname (Os.path.abspath (__file__)), Os.path.dirname (Os.path.dirname ( Os.path.abspath (__file__)) + "/New module") # Create a compressed package and return the file path, for example: zip,tar# base_name: The file name of the compressed package, or the path of the compressed package. Just the file name, save to the current directory, Otherwise, save to the specified path, # such as: www + = save to current path # such as:/user/wupeiqi/www + = Save to/user/wupeiqi/www is the package name # Format: Compressed package type, "Zip", "tar", "Bztar", "Gztar" # Root_dir: Folder path to compress (default current directory) # Owner: User, default Current user # Group: groups, default current group # Logger: Used for logging, usually logging. Logger Object # Note: The compression path does not include the path where the program is located, otherwise it will self-compress a layer of shutil.make_archive (' abc ', "Zip", Os.path.dirname (Os.path.dirname ( Os.path.abspath (__file__))) # Shelve module is a simple k,v the internal data through the file persistence module, can persist any pickle can support the Python data format import datetimeimport Shelvewith shelve.open (' shelve_test ') as D:info = {' Age ': "Job": ' it '} name = [' Alex ', ' rain ', ' Test '] d[' name '] = Name d[' Info '] = info d["date"] = Datetime.datetime.now () d = shelve.open (' shelve_test ') print (D.get (name)) Print (D.get (" Info ")) Print (D.get (" date ")) Pyyaml module Http://pyyaml.org/wiki/PyYAMLDocumentationConfigParser module for generating and modifying common configuration documents, The name of the current module is in PythoN3 change to configparser# write file import configparserconfig = Configparser. Configparser () config["DEFAULT"] = {' Serveraliveinterval ': ' A ', ' 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 ' topsecret[' ForwardX11 '] = ' no ' config[' DEFAULT ' [' ForwardX11 '] = ' Yes ' with open (' Example.ini ', ' W ') as Configfile:config.write (configfile) # Read file Import configparserconfig = Configparser. Configparser () config.read (' Example.ini ') # takes all nodes except default print (Config.sections ()) # to the contents of the default print ( Config.defaults ()) # Fetch node content print (config[' bitbucket.org ' [' User ']) # Delete node config.remove_section (' bitbucket.org ') The Config.write (' Example1.ini ', ' W ') # Hashlib module is used to encrypt related operations, replacing the MD5 module and the SHA module in 3.x, mainly providing sha1,sha224,sha256,sha384, SHA512,MD5 algorithm Import HASHLIBM = HASHLIB.MD5 () m.update (' King cover Tiger '. Encode (encoding= ' utf-8 ')) # Decimal Encryption Print (M.digest ()) # Hex-Encrypted print (M.hexdigest ()) s = hashlib. SHA1 () s.update (b ' Hello ') print (S.digest ()) print (S.hexdigest ()) # comparison Common S1 = hashlib.sha256 () s1.update (b ' Hello ') print (S1.digest ()) print (S1.hexdigest ()) # HMAC for message encryption Import Hmach = Hmac.new (b ' 12345 ', ' King of the Land Tiger '. Encode (encoding= ' utf-8 ')) Print (H.digest ()) print (H.hexdigest ()) Re module '. ' default match any character except \ n, if flag Dotall is specified, matches any character, including the newline ' ^ ' match character beginning, if Flags is specified MULTILINE, this can also be matched on (r "^a", "\nabc\neee", Flags=re. MULTILINE) ' $ ' matches the end of the character, or E.search ("foo$", "BFOO\NSDFSF", Flags=re. MULTILINE). Group () can also ' * ' match the character before the * number 0 or more times, Re.findall ("ab*", "CABB3ABCBBAC") result for [' ABB ', ' ab ', ' a '] ' + ' matches the previous character 1 or more times, Re.findall ("ab+", "Ab+cd+abb+bba") results [' AB ', ' ABB '] '? ' match the previous character 1 or 0 times ' {m} ' matches the previous character m times ' {n,m} ' matches the previous character N to M times, Re.findall ("ab{ 1,3} "," ABB ABC abbcbbb ") Results ' ABB ', ' AB ', ' ABB ' ' | ' match | Left or | The right character, Re.search ("abc| ABC "," ABCBABCCD "). Group () Results ' ABC ' (...) ' Group match, Re.search (" (ABC) {2}a (123|456) C "," abcabca456c "). Group () The result abcabca456c ' \a ' matches only from the beginning of the character, Re.search ("\aabc", "ALEXABC") is not matched to the ' \z ' match character end, the same as $ ' \d ' matches the number 0-9 ' \d ' matches the non-numeric ' \w ' match [a-za-z0- 9] ' \w ' matches non-[A-za-Z0-9] ' \s ' matches whitespace characters, \ t, \ n, \ r, Re.search ("\s+", "Ab\tc1\n3"). Group () result ' \ t ' (? P<name&gt, ...) ' Group Matching Re.search (? P<province>[0-9]{4}) (? P<city>[0-9]{2}) (? P&LT;BIRTHDAY&GT;[0-9]{4}) "," 371481199306143242 "). Groupdict (" city ") result {' Province ': ' 3714 ', ' City ': ' Bayi ', ' birthday ' : ' 1993 '}import reres = Re.match (' ^abc\d+ ', ' abc321jbakk333 ') res = Re.match (' a.+k ', ' abc321jbakk333 ') res = Re.search (' C '). +k ', ' abc321jbakk333 ') res = Re.search (' j[a-za-z]+k ', ' abc321jbaakk333 ') print (Res.group ()) res = Re.findall (' [0-9]{1,3 } ', ' AA1X2K345KKD ') print (res) res = Re.search (' (? p<id>[0-9]+) (? p<name>[a-za-z]+) ', ' [email protected] '). Groupdict () print (res) res = Re.split (' [0-9]+ ', ' Abc12de3f45gh ') Print (res) res = re.sub (' [0-9]+ ', ' | ', ' abc12de3f45gh ', count=2) print (res) res = re.search (' \\\\ ', ' Akdbsk\kdiek ') print ( Res.group ()) # ignores Case res = Re.search (' [a-z]+ ', ' Akdbska ', flags=re. I) Print (Res.group ())

Python Basic Learning

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.