A brief overview of Python's main modules and common methods

Source: Internet
Author: User
Tags md5 encryption

Original address: http://blog.csdn.net/hwhjava/article/details/22284399

************************
OS module:
Os.remove () deleting files
Os.unlink () deleting files
Os.rename () Renaming files
Os.listdir () lists all files in the specified directory
Os.chdir () Change the current working directory
OS.GETCWD () Gets the current file path
Os.mkdir () New directory
Os.rmdir () Delete empty directory (delete non-empty directory, use Shutil.rmtree ())
Os.makedirs () Create a multilevel directory
Os.removedirs () Deleting a multilevel directory
Os.stat (file) to get the properties of files
Os.chmod (file) Modify permissions
Os.utime (file) to modify timestamp
Os.name (file) Gets the operating system identity
Os.system () Executing operating system commands
OS.EXECVP () Start a new process
Os.fork () Gets the parent process ID and returns 0 in the child process return
OS.EXECVP () Execute External program script (Uinx)
Os.spawn () Execute External program script (Windows)
Os.wait () temporarily unknown
Os.path module:
Os.path.split (filename) splits the file path and filename (the last directory is separated as the file name)
Os.path.splitext (filename) splits the file path and file name extension into a single tuple
Os.path.dirname (filename) returns the directory portion of the file path
Os.path.basename (filename) returns the filename portion of the file path
Os.path.join (dirname,basename) the file path and filename into the full file path
Os.path.abspath (name) gets the absolute path
Os.path.splitunc (path) splits the path into mount point and file name
Os.path.normpath (path) canonical path string form
Os.path.exists () Determine if a file or directory exists
Os.path.isabs () returns True if path is an absolute path
Os.path.realpath (PATH) #返回path的真实路径
Os.path.relpath (path[, start]) #从start开始计算相对路径
Os.path.normcase (PATH) #转换path的大小写和斜杠
Os.path.isdir () Determine if name is a directory, name is not a directory and return false
Os.path.isfile () determines if name is not a file and does not exist return false
Os.path.islink () Determines whether the file is connected to a file, returns a Boolean
Os.path.ismount () Specifies whether the path exists and is a mount point, returning a Boolean
Os.path.samefile () is a file with the same path, returns a Boolean
Os.path.getatime () returns the most recent access time floating-point type
Os.path.getmtime () returns the last modified time floating-point type
Os.path.getctime () returns the file creation time floating-point type
Os.path.getsize () returns the file size byte units
Os.path.commonprefix (list) #返回list (multiple paths), the longest path common to all paths
Os.path.lexists #路径存在则返回True, path corruption also returns true
Os.path.expanduser (path) #把path中包含的 "~" and "~user" to the user directory
Os.path.expandvars (path) #根据环境变量的值替换path中包含的 "$name" and "${name}"
Os.path.sameopenfile (FP1, FP2) #判断fp1和fp2是否指向同一文件
Os.path.samestat (STAT1, STAT2) #判断stat tuple STAT1 and Stat2 point to the same file
Os.path.splitdrive (path) #一般用在windows下, returns a tuple of drive names and paths
Os.path.walk (path, visit, Arg) #遍历path, perform a function for each path in detail in the manual
Os.path.supports_unicode_filenames () sets whether Unicode path names are supported
Stat module:
Describes the meaning of the values in the list of file attributes returned by Os.stat ()
Filestats = Os.stat (path) Gets the list of file attributes
Filestats[stat. St_mode] Get the file mode
Filestats[stat. St_size] File size
Filestats[stat. St_mtime] File Last modified time
Filestats[stat. St_atime] File last accessed time
Filestats[stat. St_ctime] File creation time
Stat. S_isdir (Filestats[stat. St_mode]) Whether the directory
Stat. S_isreg (Filestats[stat. St_mode]) are general documents
Stat. S_islnk (Filestats[stat. St_mode]) Whether the file is connected
Stat. S_issock (Filestats[stat. St_mode]) Whether cock file
Stat. S_isfifo (Filestats[stat. St_mode]) whether to name the pipe
Stat. S_isblk (Filestats[stat. St_mode]) is a block device
Stat. S_ISCHR (Filestats[stat. St_mode]) Whether the character is set
SYS module:
SYS.ARGV command line argument list, the first element is the path of the program itself
Sys.path returns the search path for the module, using the value of the PYTHONPATH environment variable when initializing
Sys.modules.keys () returns the list of all modules that have been imported
Sys.modules returns the module field of the system import, key is the module name, value is the module
Sys.exc_info () Gets the exception class currently being processed, Exc_type, Exc_value, exc_traceback the exception details currently handled
Sys.exit (n) exit program, Exit normally (0)
Sys.hexversion gets the version value of the Python interpreter, 16 binary format such as: 0x020403f0
Sys.version get version information for Python interpreter
Sys.platform returns the operating system platform name
Sys.stdout Standard Output
Sys.stdout.write (' AAA ') standard output content
Sys.stdout.writelines () No Line break output
Sys.stdin Standard input
Sys.stdin.read () Enter a row
Sys.stderr Error Output
Sys.exc_clear () to clear current or recent error messages that are present on the current thread
Sys.exec_prefix returns the location of the platform standalone Python file installation
Sys.byteorder The local byte rule indicator, the value of the Big-endian platform is ' big ', the value of the Little-endian platform is ' little '
Sys.copyright record python copyright-related things
API version of C for the Sys.api_version interpreter
Sys.version_info ' final ' indicates the final, also ' candidate ' represents a candidate, indicating the version level, whether there is a subsequent release
Sys.getdefaultencoding () returns the default character encoding format you are currently using
Sys.getfilesystemencoding () Returns the encoded name of the Unicode file name converted to the system file name
List of built-in modules imported by the Sys.builtin_module_names Python interpreter
Sys.executable Python interpreter path
Sys.getwindowsversion () Get the version of Windows
Sys.stdin.readline () reads a line from the standard input, Sys.stdout.write ("a") screen output a
Sys.setdefaultencoding (name) is used to set the current default character encoding (use the Reference document in detail)
Sys.displayhook (value) if value is not NULL, the function will output it to sys.stdout (use the Reference document in detail)


Datetime,date,time module:
Datetime.date.today () Local Date object (with the STR function to get its literal representation (2014-03-24))
Datetime.date.isoformat (obj) Current [year-month-day] string representation (2014-03-24)
Datetime.date.fromtimestamp () Returns a Date object, the parameter is a timestamp, returns [year-month-day]
Datetime.date.weekday (obj) returns the day of the week for a Date object, Monday is 0
Datetime.date.isoweekday (obj) returns the day of the week for a Date object, Monday is 1
Datetime.date.isocalendar (obj) returns a Date object with a tuple with a month and a day
DateTime object:
Datetime.datetime.today () returns a DateTime object containing the local time (with microseconds) 2014-03-24 23:31:50.419000
Datetime.datetime.now ([TZ]) returns the DateTime object for the specified time zone 2014-03-24 23:31:50.419000
Datetime.datetime.utcnow () returns a DateTime object of 0 time zone
Datetime.fromtimestamp (Timestamp[,tz]) returns a DateTime object by timestamp, specifying the time zone, which can be used to strftime convert to a date representation
Datetime.utcfromtimestamp (timestamp) returns a Utc-datetime object by time stamp
Datetime.datetime.strptime (' 2014-03-16 12:21:21 ', '%y-%m-%d%h:%m:%s ') convert a string to a DateTime object
Datetime.datetime.strftime (Datetime.datetime.now (), '%y%m%d%h%m%s ') converts a DateTime object to a str representation
Datetime.date.today (). Timetuple () Convert to timestamp datetime tuple object, which can be used to convert timestamps
Datetime.datetime.now (). Timetuple ()
Time.mktime (Timetupleobj) to convert a DateTime tuple object to a timestamp
Time.time () Current timestamp
Time.localtime
Time.gmtime



HASHLIB,MD5 module:
HASHLIB.MD5 (' Md5_str '). Hexdigest () MD5 encryption on the specified string
MD5.MD5 (' Md5_str '). Hexdigest () MD5 encryption on the specified string

Random module:
Random.random () generates 0-1 of random floating-point numbers
Random.uniform (A, b) generates random floating-point numbers within a specified range
Random.randint (A, B) produces a random integer within a specified range
Random.randrange ([start], stop[, step]) generates a random number from a set of specified steps
Random.choice (sequence) produces a random number from the sequence
Random.shuffle (x[, random]) disrupts elements in a list
Random.sample (sequence, k) randomly fetches fragments of a specified length from a sequence

Types Module:
All data type names are saved.
If type (' 1111 ') = = types. StringType:
MYSQLDB module:
Mysqldb.get_client_info () Get API version
Mysqldb.binary (' string ') into binary data form
mysqldb.escape_string (' str ') character escaping function for MySQL
Mysqldb.datefromticks (1395842548) convert timestamp to Datetime.date object instance
Mysqldb.timestampfromticks (1395842548) convert timestamp to Datetime.datetime object instance
Mysqldb.string_literal (' str ') character escapes
Mysqldb.cursor () method on the Cursor object: "Python core programming" P624

Atexit module:
Atexit.register (FUN,ARGS,ARGS2.) Register function func, call the function before the parser exits



String module:
String module function: "Python core programming" P146
Re module:
Regular expression module function: "Python core programming" P472
Math,cmath module:
Mathematical operations, complex arithmetic functions
Operator module:
A collection of some numeric manipulation functions. Reference CSDN Collection
Copy module:
Copy.copy (a) Copying objects
Copy.deepcopy (a) Copy collection


Fileinput module:
Working with file content modules
Shutil module:
Contains some functions for copying files and folders:


Excepitions module:
Exception is the base class for all exceptions.
Systemexit (Exception) is raised by the Sys.exit () function.
StandardError (Exception) is the base class for all built-in exceptions (except Systemexit).
Lookuperror (StandardError) is the base class for a sequence or dictionary that does not contain the exception that is thrown when a given index or key.
Indexerror (Lookuperror) This exception is thrown when a sequence object fails with the given index number index.
Keyerror (Lookuperror) This exception is thrown when a Dictionary object fails with the given index index.
Nameerror (StandardError) is thrown when Python finds a global or local name failure.
Unboundlocalerror (Nameerror) This exception is thrown when a local variable is used without an assignment.
TypeError (StandardError) thrown when an action or function is applied to an object of type unsupported
Attributeerror (StandardError) This exception is thrown when a py operation fails on an instance property, method, or module.
Importerror (StandardError) Py was thrown when the module was not found or the from was unable to find the name in the module.
SyntaxError (StandardError) This exception is thrown when the interpreter encounters a syntax error at compile time.
Indentationerror (SyntaxError) is thrown when an illegal indentation is encountered.
ValueError (StandardError) is raised when a parameter type is correct but the value is not valid.
Stopiteration (StandardError) iterator error, usually appearing in the next () method or Generator method
Unicodeerror (valueerror) Unicode encoding or decoding error
Unicodeencodeerror (unicodeerror) Unicode encoding error
Unicodedecodeerror (unicodeerror) Unicode decoding error
Unicodetranslateerror (unicodeerror) encoding conversion error
EnvironmentError the base class that throws exceptions as all interpreter environments.
IOError (EnvironmentError) is used to mark I/O related errors.
OSError (EnvironmentError) is used to mark errors caused by OS modules.
Windowserror (OSError) is used to mark Windows-related errors in the OS module.
Taberror (Indentationerror) is likely to be raised when checking for inconsistent indentation with the-TT option.
Assertionerror (StandardError) is raised when an Assert statement fails (that is, when the expression is false).
Systemerror (STANDARDERROR) interpreter internal error.
Memoryerror (StandardError) throws the exception when the interpreter runs out of memory.
Keyboardinterrupt (StandardError) is raised after the user presses CONTROL-C (or other interrupt keys).
Arithmeticerror (StandardError) is the base class for mathematical computation-related anomalies.
Overflowerror (Arithmeticerror) is raised when an integer operation overflows.
Zerodivisionerror (Arithmeticerror) is thrown when you try to divide a number by 0.
Floatingpointerror (Arithmeticerror) is raised when a floating-point operation fails.
RuntimeError (StandardError) is raised when a run-time issue occurs.
Notimplementederror (RuntimeError) when a base class requires a subclass to implement some method and the subclass does not implement the method when it is raised

A brief overview of Python's main modules and common methods

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.