Consolidate the Python foundation
The following is a list of commonly used Python standard library modules, and a brief description is attached, so that we can use them.
It is recommended that every Python beginner collect a copy, this is your first treasure map.
os.remove() delete file
os.unlink() delete file
os.rename() rename file
os.listdir() lists all files in the specified directory
os.chdir() changes the current working directory
os.getcwd() Get the current file path
os.mkdir() New directory
os.rmdir() delete empty directories (to delete non-empty directories, use shutil.rmtree())
os.makedirs() creates multi-level directories
os.removedirs() delete multi-level directories
os.stat(file) Get file attributes
os.chmod(file) modify file permissions
os.utime(file) modify file timestamp
os.name(file) Get operating system identification
os.system() executes operating system commands
os.execvp() starts a new process
os.fork() gets the parent process ID and returns 0 in the return of the child process
os.execvp() Execute external program script (Uinx)
os.spawn() Execute external program script (Windows)
os.access(path, mode) Determine file permissions (refer to cnblogs for details)
os.wait() is temporarily unknown
os.path module:
os.path.split(filename) splits the file path and file name (the last directory will be separated as the file name)
os.path.splitext(filename) splits the file path and file extension into a tuple
os.path.dirname(filename) returns the directory part of the file path
os.path.basename(filename) returns the file name part of the file path
os.path.join(dirname,basename) combines the file path and file name into a complete file path
os.path.abspath(name) to get the absolute path
os.path.splitunc(path) splits the path into mount points and file names
os.path.normpath(path) standard path string form
os.path.exists() Determine whether a file or directory exists
os.path.isabs() If path is an absolute path, return True
os.path.realpath(path) #Return the real path of path
os.path.relpath(path[, start]) #Calculate the relative path from start
os.path.normcase(path) #Convert the case and slash of path
os.path.isdir() judges whether name is a directory, and returns false if name is not a directory
os.path.isfile() Determines whether name is a file, and returns false if it does not exist
os.path.islink() judges whether the file is connected to the file and returns boolean
os.path.ismount() specifies whether the path exists and is a mount point, and returns boolean
os.path.samefile() is the file with the same path, return boolean
os.path.getatime() returns the most recently accessed time floating point
os.path.getmtime() returns the last modified time float
os.path.getctime() returns the file creation time float
os.path.getsize() returns the file size in bytes
os.path.commonprefix(list) #Returns the longest path shared by all paths in the list (multiple paths)
os.path.lexists #Returns True if the path exists, and returns True if the path is damaged
os.path.expanduser(path) #Convert the "~" and "~user" contained in the path into user directories
os.path.expandvars(path) #Replace the "name" and "{name}" contained in the path according to the value of the environment variable
os.path.sameopenfile(fp1, fp2) #Judging whether fp1 and fp2 point to the same file
os.path.samestat(stat1, stat2) #Judging whether stat tuple stat1 and stat2 point to the same file
os.path.splitdrive(path) #Generally used under windows, return a tuple of drive name and path
os.path.walk(path, visit, arg) #Traverse the path and execute a function for each path. See the manual for details
os.path.supports_unicode_filenames() Set whether to support unicode path names
Describe the meaning of each value in the file attribute list returned by os.stat()
fileStats = list of file attributes obtained by os.stat(path)
fileStats[stat.ST_MODE] Get the mode of the file
fileStats[stat.ST_SIZE] File size
fileStats[stat.ST_MTIME] File last modification time
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 it a general file
stat.S_ISLNK(fileStats[stat.ST_MODE]) Whether to connect files
stat.S_ISSOCK(fileStats[stat.ST_MODE]) Whether to COCK file
stat.S_ISFIFO(fileStats[stat.ST_MODE]) is the pipe named
stat.S_ISBLK(fileStats[stat.ST_MODE]) is a block device
stat.S_ISCHR(fileStats[stat.ST_MODE]) is the character set
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, using the value of the PYTHONPATH environment variable during initialization
sys.modules.keys() returns a list of all imported modules
sys.modules returns the module field imported by the system, the key is the module name, and the value is the module
sys.exc_info() Get the exception class currently being processed, exc_type, exc_value, exc_traceback the current exception details
sys.exit(n) exit the program, exit(0) when exiting normally
sys.hexversion Get the version value of the Python interpreter, in hexadecimal format such as: 0x020403F0
sys.version Get the version information of the Python interpreter
sys.platform returns the name of the operating system platform
sys.stdout standard output
sys.stdout.write('aaa') Standard output content
sys.stdout.writelines() no newline output
sys.stdin standard input
sys.stdin.read() input one line
sys.stderr error output
sys.exc_clear() is used to clear the current or recent error messages in the current thread
sys.exec_prefix returns the location of the platform-independent python file installation
sys.byteorder is an indicator of local byte order, the value of big-endian platform is'big', the value of little-endian platform is'little'
sys.copyright records python copyright related things
sys.api_version The C API version of the interpreter
sys.version_info'final' means final, and'candidate' means candidate, indicating version level, whether there is a subsequent release
sys.getdefaultencoding() returns the current default character encoding format you are using
sys.getfilesystemencoding() returns the name of the encoding that converts Unicode file names into system file names
sys.builtin_module_names The list of built-in modules imported by the Python interpreter
sys.executable Python interpreter path
sys.getwindowsversion() Get the version of Windows
sys.stdin.readline() reads a line from standard input, sys.stdout.write("a") outputs a on the screen
sys.setdefaultencoding(name) is used to set the current default character encoding (refer to the document for details)
sys.displayhook(value) If value is not empty, this function will output it to sys.stdout (refer to the document for detailed use)
datetime.date.today() local date object, (use str function to get its literal representation (2014-03-24))
datetime.date.isoformat(obj) The current [year-month-day] string representation (2014-03-24)
datetime.date.fromtimestamp() returns a date object, the parameter is a timestamp, and returns [year-month-day]
datetime.date.weekday(obj) returns the week number of a date object, Monday is 0
datetime.date.isoweekday(obj) returns the week number of a date object, Monday is 1
datetime.date.isocalendar(obj) returns the date object as a tuple with year, month, and day
datetime object:
datetime.datetime.today() returns a datetime object containing local time (including microseconds) 2014-03-24 23:31:50.419000
datetime.datetime.now([tz]) returns the datetime object of the specified time zone 2014-03-24 23:31:50.419000
datetime.datetime.utcnow() returns a datetime object with zero time zone
datetime.fromtimestamp(timestamp[,tz]) returns a datetime object according to timestamp, can specify time zone, can be used to convert strftime to date
datetime.utcfromtimestamp(timestamp) returns a UTC-datetime object by timestamp
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') Convert datetime object to str representation
datetime.date.today().timetuple() is converted to a timestamp datetime tuple object, which can be used to convert timestamps
datetime.datetime.now().timetuple()
time.mktime(timetupleobj) convert datetime tuple object to timestamp
time.time() current timestamp
time.localtime
time.gmtime
hashlib.md5('md5_str').hexdigest() encrypts the specified string md5
md5.md5('md5_str').hexdigest() encrypts the specified string md5
random.random() Generate a random floating point number from 0-1 random.uniform(a, b) Generate a random floating point number in the specified range random.randint(a, b) Generate a random integer in the specified range random.randrange([start ], stop[, step]) Generate a random number from a set of specified steps random.choice(sequence) Generate a random number from a sequence random.shuffle(x[, random]) Shuffle the elements in a list random.sample(sequence, k) randomly obtain a fragment of the specified length from the sequence
All data type names are saved. if type('1111') == types.StringType:
MySQLdb module:
MySQLdb.get_client_info() Get API version
MySQLdb.Binary('string') converted to binary data form
MySQLdb.escape_string('str') Character escape function for MySQL
MySQLdb.DateFromTicks(1395842548) Convert the timestamp to a datetime.date object instance
MySQLdb.TimestampFromTicks(1395842548) Convert the timestamp to a datetime.datetime object instance
MySQLdb.string_literal('str') character escape
MySQLdb.cursor() method on the cursor object: "Python Core Programming" P624
atexit.register(fun,args,args2..) Register function func, which is called before the parser exits
str.capitalize() capitalize the first character of the string
str.center(width) returns a new string with the original string centered and padded to width with spaces
str.ljust(width) returns a new string with the original string justified to the left and padded with spaces to the specified length
str.rjust(width) returns a new string with the original string right-justified and filled with spaces to the specified length
str.zfill(width) returns the string to be right-justified, and the new string is filled with 0 in front to the specified length
str.count(str,[beg,len]) returns the number of occurrences of the substring in the original string, beg,len is the range
str.decode(encodeing[,replace]) decode string, error raises ValueError
str.encode(encodeing[,replace]) decode string
str.endswith(substr[,beg,end]) Whether the string ends with substr, beg,end is the range
str.startswith(substr[,beg,end]) Whether the string starts with substr, beg,end is the range
str.expandtabs(tabsize = 8) convert the tabs of the string to spaces, the default is 8
str.find(str,[stat,end]) Find the position of the first occurrence of the substring in the string, otherwise return -1
str.index(str,[beg,end]) Find the position of the substring in the specified character, and report an exception if there is no
str.isalnum() checks whether the string is composed of letters and numbers, returns true otherwise False
str.isalpha() checks whether the string is composed of pure letters, returns true, otherwise false
str.isdecimal() checks whether the string is composed of pure decimal numbers and returns a boolean value
str.isdigit() checks whether the string is composed of pure numbers and returns a Boolean value
str.islower() checks whether the string is all lowercase and returns a boolean
str.isupper() checks whether the string is all uppercase and returns a boolean
str.isnumeric() checks whether the string contains only numeric characters and returns a Boolean value
str.isspace() If str contains only spaces, it returns true, otherwise FALSE
str.title() returns a titled string (all words are capitalized, and the rest are lowercase)
str.istitle() returns true if the string is titled (see title()), otherwise false
str.join(seq) uses str as a concatenator to connect elements in a sequence into a string
str.split(str='',num) uses str as the separator to separate a string into a sequence, and num is the separated string
str.splitlines(num) is separated by lines and returns a list of the contents of each line as elements
str.lower() converts uppercase to lowercase
str.upper() converts the lowercase of the string to uppercase
str.swapcase() Switch the case of a string
str.lstrip() removes the space and carriage return and line feed on the left of the character
str.rstrip() removes the spaces on the right side of the character and the carriage return and line feed
str.strip() removes spaces and carriage returns and line feeds on both sides of the character
str.partition(substr) Divides str into a 3-tuple from the first position where substr appears.
str.replace(str1,str2,num) Find str1 to replace str2, num is the number of replacements
str.rfind(str[,beg,end]) Query the substring from the right
str.rindex(str,[beg,end]) Find the position of the substring from the right
str.rpartition(str) is similar to the partition function, but searches from the right
str.translate(str,del='') Convert the characters of string according to the table given by str, del is the character to be considered
urllib.quote(string[,safe]) encodes the string. The parameter safe specifies characters that do not need to be encoded
urllib.unquote(string) decode the string
urllib.quote_plus(string[,safe]) is similar to urllib.quote, but this method uses'+' to replace '', and quote uses'%20' to replace' '
urllib.unquote_plus(string) decodes the string
urllib.urlencode(query[,doseq]) Convert a dict or a list of tuples containing two elements into url parameters.
For example, the dictionary {'name':'wklken','pwd':'123'} will be converted to "name=wklken&pwd=123"
urllib.pathname2url(path) converts a local path into a url path
urllib.url2pathname(path) converts url path to local path
urllib.urlretrieve(url[,filename[,reporthook[,data]]]) download remote data to local
filename: Specify the path to save to the local (if not specified, urllib generates a temporary file to save the data)
reporthook: callback function, which will be triggered when the server is connected and the corresponding data block transmission is completed
data: refers to the data posted to the server
rulrs = urllib.urlopen(url[,data[,proxies]]) grab web page information, [data]post data to the proxy set by Url,proxies
urlrs.readline() is used the same as file object
urlrs.readlines() is the same as the file object
urlrs.fileno() is used the same as file object
urlrs.close() is the same as the file object
urlrs.info() returns a httplib.HTTPMessage object, representing the header information returned by the remote server
urlrs.getcode() Get the HTTP status code returned by the request
urlrs.geturl() returns the requested URL
1. Commonly used regular expression symbols and syntax:'.'** matches all strings, except \n**
'-' means the range [0-9]'*' matches the preceding sub-expression zero or more times. To match * characters, use *. '+' matches the preceding sub-expression one or more times. To match the + character, use +'^' to match the beginning of the string
'$' matches the end of the string re'' escape character, so that the latter character changes its original meaning, if there is a character * in the string that needs to be matched, you can * or the character set [] re.findall(r'3 *','3ds') knot ['3*']
'' Match the preceding character 0 or more times re.findall("ab","cabc3abcbbac") Result: ['ab','ab','a']
'?' matches the previous string 0 times or 1 time re.findall('ab?','abcabcabcadf') result ['ab','ab','ab','a']
'{ m)' Match the previous character m times re.findall('cb{1}','bchbchcbfbcbb') result ['cb','cb']
'{ n,m}' matches the previous character n to m times re.findall('cb{2,3}','bchbchcbfbcbb') result ['cbb']
'\ d'matches a number, equal to [0-9] re.findall('\d','Phone: 10086') result ['1', '0', '0', '8', '6']
'\ D'matches a non-digit, equal to [^0-9] re.findall('\D','Phone:10086') result ['电','话',':']
'\ w'matches letters and numbers, equal to [A-Za-z0-9] re.findall('\w','alex123,./;;;') result ['a','l','e', 'x', '1', '2', '3']
'\ W'matches non-English letters and numbers, equal to [^A-Za-z0-9] re.findall('\W','alex123,./;;;') result [',','.', ' /',';',';',';']
'\ s'matches blank characters re.findall('\s','3*ds \t\n') result ['','\t','\n']
'\ S'matches non-blank characters re.findall('\s','3ds \t\n') result ['3','','d','s']
'\ A'matches the beginning of the string
'\ Z'matches the end of the string
'\ b'matches the beginning and end of a word. A word is defined as an alphanumeric sequence, so the end of the word is represented by blanks or non-alphanumeric characters
'\ B'is the opposite of \b, only matches when the current position is not on the word boundary
'(? P
[] It defines the range of characters to match. For example, [a-zA-Z0-9] means that the character at the corresponding position must match English characters and numbers. [\s*] means space or *.
**2. Commonly used re function: **
Method/attribute role
re.match(pattern, string, flags=0) match from the beginning of the string, if the match is not successful at the beginning, match() returns none
re.search(pattern, string, flags=0) scan the entire string and return the first successful match
re.findall(pattern, string, flags=0) find all strings that match RE and return them as a list
re.finditer(pattern, string, flags=0) find all strings that match RE and return them as an iterator
re.sub(pattern, repl, string, count=0, flags=0) replace the matched string
ceil: take the smallest integer value greater than or equal to x, if x is an integer, return x
copysign: add the sign of y to the front of x, you can use 0
cos: find the cosine of x, x must be radians
degrees: convert x from radians to angles
e: represents a constant
exp: return math.e, which is 2.71828 to the power of x
expm1: returns the value of x (its value is 2.71828) power of math.e minus 1
fabs: returns the absolute value of x
factorial: take the value of the factorial of x
floor: take the largest integer value less than or equal to x, if x is an integer, return itself
fmod: get the remainder of x/y, its value is a floating point number
frexp: returns a tuple (m, e), which is calculated as: x is divided by 0.5 and 1, respectively, to get a range of values
fsum: Summing each element in the iterator
gcd: returns the greatest common divisor of x and y
hypot: If x is not an infinite number, return True, otherwise return False
isfinite: If x is positive infinity or negative infinity, return True, otherwise return False
isinf: If x is positive infinity or negative infinity, return True, otherwise return False
isnan: If x is not a number True, otherwise return False
ldexp: return the value of x*(2**i)
log: returns the natural logarithm of x, the default is e as the base, when the base parameter is given, the logarithm of x is returned to the given base, the calculation formula is: log(x)/log(base)
log10: Returns the base 10 logarithm of x
log1p: returns the value of the natural logarithm (base e) of x+1
log2: returns the base 2 logarithm of x
modf: returns a tuple consisting of the fractional part and the integer part of x
pi: numeric constant, pi
pow: return x to the power of y, that is x**y
radians: Convert angle x to radians
sin: find the sine of x (x is radians)
sqrt: find the square root of x
tan: Returns the tangent of x (x is radians)
trunc: returns the integer part of x
Recommended Posts