Time module:
in Python, there are usually several ways to represent the time:
1, time stamp, such as Time.time
2. Formatted time string, e.g. ' 17/01/2017 10:17:00 '
3, tuples (struct_time), such as Gmtime, localtime, etc.
Time.time (): Converts all time from 1970 to present to the number of seconds, i.e. timestamp
Time.gmtime (): Converts the timestamp (in seconds) to the tuple form of the UTC time Zone
Time.localtime (): Converts a timestamp into a tuple form in the local time zone
This tuple form of time can be achieved through its internal method of the required time element. Cases:
x = Time.localtime ()
X.tm_year can get what year it is now
X.tm_mon can get the current month
X.tm_mday can get the current day
Time.sleep (s): sleep s S
Time.mktime (t): Convert time in tuple (tuple) to timestamp
Time.strftime (format [, tuple]):
Converts the time in the form of a tuple to a formatted time string (displayed numerically) and converts the current localtime if no tuple is specified
Time.strptime (String, format): Converts a formatted time string to a time in the form of a Narimoto group
Time.asctime ([tuple]):
Converts the time of the tuple form to a formatted time string (shown in English) and converts the current localtime if no tuple is specified
Time.ctime ([seconds]):
Converts the timestamp to a formatted time string (shown in English) and converts the current timestamp if no time stamp is specified
DateTime module:
Datetime.datetime.now (): Gets the current date and time
Datetime.datetime.now () + Datetime.datetime.delta (3): Current time after three days
Datetime.datetime.now () + Datetime.datetime.delta (-3): Current time made three days ago
Datetime.datetime.now () + Datetime.datetime.delta (hours=3): Gets the current time after three hours
Datetime.datetime.now () + Datetime.datetime.delta (hours=-3): Get current time three hours ago
Datetime.datetime.now (). Replace (minute=10,hour=10): Time substitution
Random module: Stochastic number
Random.random (): Gets a floating-point random number between 0-1
Random.uniform (1,10): Gets a floating-point random number between 1-10, 1 and 10 can be arbitrarily specified
Random.randint (1,3): get arbitrary random numbers between 1-3, including 1 and 3, where 1 and 3 can be arbitrarily specified
Random.randrange (1,3): obtain arbitrary random numbers between 1-3, excluding 3, where 1 and 3 can be arbitrarily specified
Random.choice (' equence): Randomly take an element from the sequence sequence
Random.sample (Sequence,count): Random count of elements from sequence sequence each time
Random.shuffle (Sequence): Shuffle, disrupt the order of a sequence
OS module: Provides an interface for invoking the operating system
OS.GETCWD (): Gets the current working directory
Os.chdir (PATH): Switch directory
Os.curdir: Returns the current directory
Os.pardir: Returns the parent directory of the current directory
Os.makedirs (name, mode=511, Exist_ok=false): Create a directory recursively
Example: Os.makedirs (R '/a/b/c/d/e ')
Os.removedirs (name): If the directory is empty then delete, and recursively to the previous level of the directory, if it is empty then delete, and so on
Os.mkdir (Path, mode=511, *, Dir_fd=none): Creates a single-level directory that throws an exception if the parent directory does not exist
Os.rmdir (Path, *, Dir_fd=none): Deletes a single-level empty directory and throws an exception if the directory is not empty
Os.listdir (Path=none): Lists all files under a path, including files and directories
Os.remove (): Delete a file
Os.rename (' oldname ', ' newname '): Renaming files/directories
Os.stat (' Path/to/filename '): Get File/directory information
OS.SEP: Output operating system-specific path delimiter, win under ' \ \ ', Linux for '/'
OS.LINESEP: Output The line terminator used by the current platform, win under ' \ r \ n ', Linux for ' \ n '
OS.PATHSEP: Outputs a string used to split the path of a file, separating different paths when storing multiple paths
Os.name: The output string indicates the current usage platform. Win--> ' nt ',linux--> ' POSIX '
Os.system (' Bash Command '): Run the shell command to display the results directly
Os.environ: Getting system environment variables
Os.path.abspath (PATH): Returns the absolute path normalized by path
Os.path.split (PATH): Returns a 2-element tuple that splits the path into directories and filenames as elements
Os.path.dirname (PATH): Returns the directory of path. is actually the first element of Os.path.split (path)
Os.path.basename (PATH): Returns the last file name of path. If path ends with a/or \, then a null value is returned.
is actually the second element of Os.path.split (path)
Os.path.exists (PATH): Determines if path exists, exists return true, otherwise returns false
Os.path.isabs (PATH): Determines if path is an absolute path, returns true, otherwise false
Os.path.isfile (PATH): Determines if path is not a file, yes returns true, otherwise false
Os.path.isdir (PATH): Determines if path is a directory, yes returns TRUE, otherwise returns false
Os.path.join (path1 [, path2 [, ...]) :
When multiple paths are combined, the parameters before the first absolute path are ignored
Os.path.getatime (PATH): Returns the last access time of the file or directory to which path is pointing
Os.path.getmtime (PATH): Returns the last modified time of the file or directory to which path is pointing
SYS module:
SYS.ARGV: Command line argument list, the first element is the path of the program itself
Sys.exit (N): Exit program, Exit normally (0)
Sys.version: Get version information for Python interpreter
Sys.maxint: the largest int value
Sys.path: Returns the search path for the module, using the value of the PYTHONPATH environment variable when initializing
Sys.platform: Returns the operating system platform name
Sys.stdout.write (' please: ')
VA1 = Sys.stdin.readline () [:-1]
Shutil: Specially used to copy files, can compress package
Shutil.copyfileobj (fsrc,fdst [, length]):
Copy the contents of the FFSRC to the FDST, and you can set the number of copies by length.
Shutil.copyfile (SRC,DST): copy src to DST
Shutil.copymode (SRC,DST): Copy only permission. The content, group, and user of the new file are the same (who created the file)
Shutil.copystat (SRC,DST): Copy status information, including mode Bits,atime,mtime,flags
Shutil.copy (SRC,DST): Copying Files and Permissions
Shutil.copy2 (SRC,DST): Copying Files and status information
Shutil.copytree (src,dst,symlink=false,ignore=none): Recursive de-Copying files
Shutil.rmtree (path [, ignore_errors [, OnError]): To remove files recursively
Shutil.move (SRC,DST): To move files recursively
Shutil.make_archive (Base_name,format,...) : 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 to the compressed package. Only the file name is saved to the current directory, otherwise it is saved to the specified path.
For example: www + = Save to Current path
such as:/users/sean/www = Save to/users/sean/www
Format: Compressed package type. ' Zip ', ' tar ', ' bztar ', ' Gztar '
Root_dir: directory path to compress (default current directory)
Owner: User. Default Current User
Group: Groups. Default Current Group
Logger: Used to log logs. Usually a logging. Logger Object
Shutil Processing of compressed packets is done by calling the ZipFile and Tarfile two modules.
ZipFile module:
Compression:
z = zipfile. ZipFile (' Test.zip ', ' W ')
Z.write (' A.log ')
Z.write (' Data.data ')
Z.close ()
Extract:
z = zipfile. ZipFile (' Test.zip ', ' R ')
Z.extractall ()
Z.close ()
Tarfile module:
Compression:
tar = Tarfile.open (' Your.tar ', ' W ')
Tar.add ('/users/sean/www.zip ', arcname= ' Www.zip ')
Tar.add ('/users/sean/cmdb.zip ', arcname= ' Cmdb.zip ')
Tar.close ()
Extract:
tar = Tarfile.open (' Your.tar ', ' R ')
Tar.extractall ()
Tar.close ()
JSON & Pickle: Two modules for serialization
JSON, used to convert between string and Python data types
Converts data types in Python memory to strings stored on hard disk files
It solves the problem of data exchange between different languages and different platforms.
Pickle for conversion between Python-specific types and Python data types
Converts any data type in Python memory to a string stored on a file on the hard disk
Both provide four functions: dumps, dump, loads, load
Shelve: A Simple dictionary-type (key,value) module that stores memory data through file persistence
Can persist any Python data types that pickle can support
Write:
D = Shelve.open (' shelve_test ') #打开一个文件class Test (object):d EF __init__ (self,n): SELF.N = NT = Test (123) t2 = Test (1234567) name = [' Tom ', ' Jerry ', ' Test ']d[' test '] = name #持久化列表d [' t1 '] = t #持久化类d [' t2 '] = T2d.close ()
Read:
D.get (' Test ') d.get (' T1 ') d.get (' T2 ')
XML: Used to process XML in Python
Import Xml.etree.ElementTree as Ettree = Et.parse (' xmltest.xml ') #要处理的文件名root = Tree.getroot () print (Root.tag) #打印根标签名 # Traverse the XML document for the child in Root:print (Child.tag,child.attrib) for I in Child:print (I.tag,i.text) #只遍历year节点for node in Root.iter (' year '):p rint (Node.tag,node.text) #修改for node in Root.iter (' year '): new_year = Int (node.text) + 1node.text = str (new_ Year) Node.set ("Updated_by", "Sean") 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 ')
Configparser: Generating and modifying common configuration documents
Generated:
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:
conf = Configparser. Configparser () conf.read (' Example.ini ') print (Conf.defaults ()) print (conf[' bitbucket.org ' [' User '])
Hashlib: For encryption-related operations
The 3.x series replaces the MD5 module and the SHA module in the 2.x series. Mainly provides SHA1, SHA224, SHA256, SHA284, SHA512 and MD5 algorithms
Import HASHLIBM = Hashlib.md5 () m.update (b ' Hello ') m.update (b "It ' s Me") print (M.digest ()) #二进制格式hashprint (M.hexdigest ( )) #十六进制格式hash
Note: The result of the previous two update before printing, the result is two times the object of the update is added together to generate the hash
This article is from the "Home" blog, please make sure to keep this source http://itchentao.blog.51cto.com/5168625/1897288
Python common modules ingest