Python main modules and methods

Source: Internet
Author: User
Tags local time shuffle stdin

Py Core Module Method ********************os module: os.remove () Delete file Os.unlink () Delete file Os.rena    Me () Rename file Os.listdir () lists all files under the specified directory Os.chdir () changes 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 () to create a multilevel directory Os.remo Vedirs () Delete multi-level directory Os.stat (file) Get file properties Os.chmod (file) modify file permissions Os.utime (file) modify file timestamp ( File) Gets the operating system identity Os.system () executes the operating system command OS.EXECVP () starts a new process os.fork () Gets the parent process ID, which is returned in the child process Returns 0 OS.EXECVP () Execute External program script (Uinx) os.spawn () Execute External program script (Windows) os.access (path, mode) to determine file permissions (refer to CNB for details) Logs) 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.sp      Litext (filename) splits the file path and file name extension into a 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) Gets the file path and filename together into the full file path Os.path.abspath (name) to get the absolute path Os.path.splitunc (path) Path segmentation is the mount point and filename os.path.normpath (PATH) specification path string Form os.path.exists () determines whether a file or directory exists Os.path.isabs () If path is an absolute path, return true Os.path.realpath (path) #返回path的真实路径 Os.path.relpath (path[, start]) # Calculates the relative path from start os.path.normcase (path) #转换path的大小写和斜杠 Os.path.isdir () to determine if name is a directory, name does not Is the directory that returns false Os.path.isfile () to determine if name is not a file, does not exist return False Os.path.islink () to determine whether the file is connected to the file, return Bo    Olean Os.path.ismount () specifies whether the path exists and is a mount point, returns a Boolean os.path.samefile () if the file is the same path, and returns a Boolean              Os.path.getatime () returns the last access time float 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), all The longest path shared by path is Os.path.Lexists #路径存在则返回True, path corruption also returns true Os.path.expanduser (path) #把path中包含的 "~" and "~user" into the user directory Os.pat H.expandvars (path) #根据环境变量的值替换path中包含的 "$name" and "${name}" Os.path.sameopenfile (FP1, FP2) #判断fp1和fp2是否指向同一文件 OS . Path.samestat (STAT1, STAT2) #判断stat if the tuple stat1 and Stat2 point to the same file os.path.splitdrive (path) #一般用在windows下, return the drive name and path Os.path.walk (path, visit, Arg) #遍历path, perform a function for each path in detail see manual os.path.supports_unicode_filenames () setting whether UNI is supported Code path name STAT module: Describes the meaning of the values in the list of file attributes returned by Os.stat () Filestats = os.stat (path) Gets the file attribute list Filestats[stat. St_mode] Gets the mode filestats[stat of the file. St_size] File size filestats[stat. St_mtime] File was last modified on Filestats[stat. St_atime] File last access time Filestats[stat. St_ctime] File creation time Stat. S_isdir (Filestats[stat. St_mode]) is the directory Stat. S_isreg (Filestats[stat. St_mode]) is the general file Stat. S_islnk (Filestats[stat. St_mode]) is connected to file Stat. S_issock (Filestats[stat. St_mode])     Whether to 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 sets the Sys module: SYS.ARGV command line parameter list, the first element is the path of the program itself Sys.path returns the search path of the module, the initialization of the Use the value of the PYTHONPATH environment variable Sys.modules.keys () to return the list of all modules that have been imported Sys.modules returns the module field of the system import, key is the module name, and value is the module sy S.exc_info () Gets the exception class currently being processed, Exc_type, Exc_value, exc_traceback the exception details currently handled Sys.exit (n) exit the program, exit normally (0 Sys.hexversion gets the version value of the Python interpreter, 16 binary format such as: 0x020403f0 sys.version Gets the version information of the Python interpreter SYS.PLATF ORM returns the operating system platform name Sys.stdout standard output sys.stdout.write (' AAA ') standard output sys.stdout.writelines () No Line break         Output Sys.stdin standard input () input one line sys.stderr error output sys.exc_clear () Used to clear the current or most recent error message that appears on the current thread Sys.exec_prefix returns the location of the platform standalone Python file installation Sys.byteorder 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 sys.api_version explanation The API version of C of the Sys.version_info ' final ' means final, also ' candidate ' represents the candidate, indicating the version level, whether there is a subsequent release sys.getdefaultencoding () return The default character encoding format that you are currently using sys.getfilesystemencoding () returns the encoded name of the Unicode file name converted to the system file name Sys.builtin_module_names Python The list of built-in modules for the interpreter import sys.executable python interpreter path sys.getwindowsversion () Gets the version of Windows SYS.STD     In.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: () The local Date object (with the STR function can get its literal representation (2014-03-24)) (obj) The current [year-month-day] string representation (2014-03-24) DATETIME.D Ate.fromtimestamp () Returns a Date object, the parameter is a timestamp, and returns the day of the week for which the [year-month-day] (obj) returns a Date object, Monday is 0 Weekday (obj) returns a Date object'sDays of the week, Monday is 1 (obj) returns a Date object with a tuple datetime object with a month and date: () returns a containing local time DateTime object (with microseconds) 2014-03-24 23:31:50.419000 ([TZ]) returns the DateTime object for the specified time zone 2014-03-24 23:31:50.4190 Datetime.datetime.utcnow () returns a DateTime object of 0 time zone Datetime.fromtimestamp (Timestamp[,tz]) returns a DateTime object by timestamp , you can specify a time zone that can be used for strftime conversions to date representations Datetime.utcfromtimestamp (timestamp) to return a Utc-datetime object by timestamp DATETIME.DATETIME.STRP Time (' 2014-03-16 12:21:21 ', "%y-%m-%d%h:%m:%s") converts the string to a DateTime object Datetime.datetime.strftime ( ( ), '%y%m%d%h%m%s ') converts a DateTime object to a str representation of (). Timetuple () converts to a timestamp datetime tuple object, which can be used to convert the timestamp da            (). Timetuple () time.mktime (timetupleobj) Convert a DateTime tuple object to a timestamp time.time () Current timestamp time.localtime time.gmtime hashlib,md5 module: hashlib.md5 (' Md5_str '). Hexdigest () to the specified string MD5 Encrypt md5.md5 (' Md5_str '). HexdIgest () MD5 cryptographic random module for the specified string: random.random () generates 0-1 of the random floating-point number Random.uniform (A, B) produces the specified range The random floating-point number Random.randint (A, b) within the specified range generates random numbers Random.randrange ([start], stop[, step]) from a set of specified steps.  Choice (sequence) generates a random number random.shuffle (x[, Random]) from a sequence to shuffle a list of elements random.sample (sequence, k) to randomly fetch 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 M The ysqldb.escape_string (' str ') character escape function for MySQL mysqldb.datefromticks (1395842548) turns the timestamp into a object instance MySQLd B.timestampfromticks (1395842548) convert timestamp to Datetime.datetime object instance mysqldb.string_literal (' str ') character escapes mysqldb.curs   method on the or () Cursor object: "Python core Programming" P624 atexit module: Atexit.register (FUN,ARGS,ARGS2.) Registers the function func, which invokes the function before the parser exits the string module: Str.capitalize () capitalizes the first character of the string (width), returns an original string centered, and padding to wid with spacesTh length of the new string Str.ljust (width) returns an original string left-aligned, padded with spaces to the specified length of the new string Str.rjust (width) returns an original string right-aligned with a space padding to the specified length    The new string Str.zfill (width) returns the string right-aligned, preceded by a 0 padding to the specified length of the new string Str.count (Str,[beg,len]) to return the substring in the original string occurrences, Beg,len is the range Str.decode (Encodeing[,replace]) decodes string, error throws ValueError exception Str.encode (Encodeing[,replace]) decoding string Str.endswith (su Bstr[,beg,end]) Whether the string ends with Substr, Beg,end is the range Str.startswith (Substr[,beg,end]) string to start with substr, Beg,end is the range Str.expandtab S (tabsize = 8) Turns the tab of the string into a space, the default is 8 Str.find (Str,[stat,end]) finds the substring where the string first appears, otherwise returns-1 Str.index (str,[beg,e               ND]) to find the position of the substring in the specified character, there is no report exception Str.isalnum () checks whether the string is composed of letters and numbers, is true otherwise false str.isalpha () Checks whether the string is composed of pure letters, returns TRUE, or false str.isdecimal () checks whether the string is made up of a pure decimal number and returns a Boolean value Str.isdigit () check Checks whether the string is composed of a pure number, returns a Boolean value Str.islower () to check whether the string is all lowercase, returns a Boolean value Str.isupper () checks whether the string is all uppercase, returns a Boolean value St           R.isnumeric ()  Checks whether the string contains only numeric characters, returns a Boolean value of Str.isspace () returns True if Str contains only spaces, or false Str.title () returns the heading string (All words capitalized, remaining lowercase) str.istitle () returns True if the string is heading (see Title ()), otherwise false str.join (SEQ) with Str as A connector that joins elements of a sequence into a string Str.split (str= ", num) with Str as a delimiter, separates a string into a sequence, and Num is a delimited string str.splitlines (num) separated by rows              , returns the contents of each row as a list of elements Str.lower () uppercase to lowercase str.upper () converts a string to lowercase str.swapcase () The capitalization of the string Str.lstrip () strips the left and carriage return characters str.rstrip () removes the space to the right of the character and the carriage return line character Str.strip    () Remove the space on both sides of the character and carriage return newline character str.partition (substr) divides str into a 3-tuple from the first position appearing in substr.    Str.replace (str1,str2,num) Find str1 Replace with Str2,num is the number of replacements Str.rfind (Str[,beg,end]) query substring from the right side Str.rindex (Str,[beg,end]) Find substring position str.rpartition (str) similar to the partition function from the right, but find Str.translate (str,del= ") from the right to convert a string of strings by the table given by str Characters, Del is the character to be Urllib module: Urllib.quote (striNg[,safe]) to encode a string. The parameter safe specifies the character urllib.unquote (string) that does not need to be encoded to decode the string Urllib.quote_plus (String[,safe]) and URLLIB.Q Uote is similar, but this method uses ' + ' to replace ', while quote uses '%20 ' instead of ' Urllib.unquote_plus (string) to decode the string Urllib.urlencode (query[,d                                            OSEQ]) Converts a dict or a list of tuples containing two elements into a URL parameter.    For example, the dictionary {' name ': ' Wklken ', ' pwd ': ' 123 '} will be converted to "name=wklken&pwd=123" Urllib.pathname2url (path) to convert the local path to a URL path Urllib.url2pathname (path) download remote data for URL path conversion cost path Urllib.urlretrieve (Url[,filename[,reporthook[,data]]) to local filename: Specifies the path to be saved locally (Urllib generates a temporary file to hold the data if not specified) Reporthook: callback function that triggers the callback data when the server is connected and the corresponding chunk is transferred:    Refer to post to server data Rulrs = Urllib.urlopen (url[,data[,proxies]) crawl web information, [data]post data to Url,proxies Settings Agent Urlrs.readline () As with a file object Urlrs.readlines () is used just like a file Object Urlrs.fileno () is used as a file object Urlrs.close () As with a file object urlrs.i NFO () returns a httplib. HTTThe Pmessage object that represents the header information returned by the remote server Urlrs.getcode () Gets the request return status HTTP status code Urlrs.geturl () return the requested URLURLLIB2 module: Urlparse module: Re module: Regular expression module function: Python core programming P472math,cmath module: Mathematical operation, complex operation function operator module: A collection of numeric manipulation functions. Reference csdn Collection Copy module: Copy.copy (a) Copy Object Copy.deepcopy (a) Copy collection Fileinput module: Processing file content Module Shutil module: Contains some copies of files and folders The function:


Original address:

Python main modules and methods

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: 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.