Explanation of common modules in python 1. Explanation of python modules

Source: Internet
Author: User

Explanation of common modules in python 1. Explanation of python modules

1.Time Module

Import times = time. localtime () # convert the time to the formatted time. get the time in struct_time format, such as year, month, and day. struct_time (maid = 2018, tm_mon = 3, tm_mday = 11, tm_hour = 19, tm_min = 53, tm_sec = 31, tm_wday = 6, tm_yday = 70, tm_isdst = 0) s = time. gmtime () # UTC time zone s = time. time () # returns the current timestamp print (time. asctime () # receive struct_time into Sun Mar 11 19:46:08 2018 do not pass the default current time print (time. ctime (0) # Return the current time Sun Mar 11 19:46:08 2018 if the default current time is passed in the timestamp format number, convert it to the timestamp date Thu Jan 1 08:00:00 1970 print (time. strftime ("% Y-% m-% d", time. localtime () # convert the struct_time format to the custom time format print (time. strptime ("2017-12-12", "% Y-% m-% d") # convert string format to struct_time format

2. datetime Module

Import datetimes = datetime. datetime. now () #(20:19:10. 993661) s many methods below year mouth day date () = 2018-03-11 ctime () = Sun Mar 11 19:46:08 2018 strftime ("% Y-% m-% d") print (datetime. date. fromtimestamp (time. time () # convert a timestamp to 2013-3-11 ################ mainly the time calculation s = datetime. datetime. now () print (s. timetuple () # time. struct_time (maid = 2018, tm_mon = 3, tm_mday = 11, tm_hour = 20, # tm_min = 19, tm_sec = 9, tm_wday = 6, tm_yday = 70, tm_isdst =-1) print (s + datetime. timedelta (seconds = 1) # The Result of the operation is followed by day hours secondsd = datetime. datetime. now () t = d. replace (year = 2016) # modify the time and return the modified time. The modified time remains unchanged. print (t)

3. Use of the random Module

Import random print (random. randint (1,200) # randomly generated numbers between 1 and 200 include print (random. randrange (1,200, 2) # randomly generated 1-200 (even) does not contain 200 print (random. random () # print (random. choice ("dasdadsasdad") # randomly select the character print (random. sample ("adasdasdasdad", 5) # list of 5 Characters randomly selected from the string # implement the verification code import stringprint (string. ascii_letters) # print (string. hexdigits) # hexadecimal print (string. digits) # decimal s_list = random. sample (string. ascii_letters + string. digits, 4) s = ''. join (s_list) print (s)
List_all = [I for I in range (80)] # a = 'dasdasdasd' # It cannot be a string # random. shuffle (list_all) # shuffles to take effect in the original list # print (list_all)
The OS module provides many functions that allow direct interaction between your program and the operating system.
# The OS module provides many functions that allow direct interaction between your program and the operating system. import osBASE_DIR = OS. path. abspath (_ file _) # Return the file's data pair path OS. listdir (". ") # list the operating systems in the specified folder. path. join ('aaa', 'aaa') # concatenate the path into the OS. path. dirname (BASE_DIR) # The returned directory path does not contain the file OS. path. split (BASE_DIR) # returns a list of OS consisting of file names and paths. path. exists (BASE_DIR) # determine whether the path exists OS. path. isfile (BASE_DIR) # determine whether the file exists in OS. path. isdir (BASE_DIR) # determine whether it is a directory OS. path. splitext (BASE_DIR) OS. path. basename (BASE_DIR) # Get the file name OS. path. getsize (BASE_DIR) # Get the file size ******** common
5. Use of the SYS module
Sys. argv command line parameter List. The first element is the program path sys. exit (n) exit the program. exit (0) sys when the program Exits normally. obtain the version information of the Python interpreter sys. the maximum Int value of maxint sys. path: return the search path of the module. during initialization, use the value of the PYTHONPATH environment variable sys. platform returns the name of the operating system platform sys. stdout. write ('Please: ') # The standard output leads to an example of a progress bar. Note: it cannot be performed on py3. You can use print instead of val = sys. stdin. readline () [:-1] # standard input sys. getrecursionlimit () # obtain the maximum number of recursive layers sys. setrecursionlimit (1200) # set the maximum number of recursive layers sys. getdefaultencoding () # Get the interpreter's default code sys. getfilesystemencoding # Get the default encoding of memory data stored in the file
The serialization and deserialization modules of json & pickle modules are used for interaction between programs.
Json is supported in different languages across platforms. json is determined by the fact that there are not many supported types. str int list tuple dict
Json. loads () can be converted into a string of json file type json. load () json. dumps () json. dump ()
Pickle can only use data types that support python in python, occupying a large volume
Import jsonimport pickle # json is supported in different languages across platforms. json is determined to support a small number of types. str int list tuple dict # json. loads () transmission can be converted into a string json file type json. load () json. dumps () json. dump () # pickle can only use data types that support python in python, occupying a large volume d = {1: 2, 3: 4} l = ["name ", "age"] s = json. dumps (d) # convert the dictionary format to print (s) d1 = json. loads (s) # converts a string to the dictionary form print (d1) f = open ("test. json ", 'w') # convert a file in the form of a dictionary into a string into a json character. dump (d, f) f. close () f = open ("test. json ", 'R') # Read from the file and convert it into a string d2 = json. load (f) # this is also the way pickle is stored in the file when the file is uploaded.

The shutil module is used to copy and compress files. It is mainly used for packaging, moving, and other functions of files.

Import shutil # copy a file only if the file must be opened and passed through the shutil handle. copyfileobj (open ("Log. py "," r "), open (" Log_new.py "," w ") # copy the file to encapsulate the shutil. copyfile ("Log. py "," log_new.py ") shutil. copymode ("Log. py "," lll. py ") # only copy permission. The target file must have shutil. copy ("Log. py "," lll. py ") # copy files and permissions. copy2 ("Log. py "," lll. py ") # copy the file and status # The copy directory must be the shutil directory. copytree (".. /FTP "," ftp ", ignore = shutil. ignore_patterns ("_ init __. py ") # recursively copy a file with the ignore = shutil parameter. ignore_patterns ("_ init __. py ") ignored file shutil. rmtree ("log_new.y") # Delete shutil. move ("log_new.y", "ll. py ") # Move the file, or rename shutil. make_archive (base_name = "log_l", format = "zip", root_dir = ".. /FTP ") # compressed file # base_name specifies the end of the compressed path and the compressed file name, format = compression format" zip "," tar "," bztar ", "gztar" # root_dir file path (directory) owner user name group name to be compressed

Module xlrd: the module that reads the excel table xlrd external module requires pip installation to only read excle

Other Excel write modification module please link http://blog.csdn.net/yankaiwei120/article/details/52204427

Import xlrd # The xls table file parsing module writes data using xlrd using xlwdBook = xlrd. open_workbook (r "C: \ Users \ zhuangjie23261 \ Desktop \ risk control document .xls") # open the file and return a book object sheet = Book. sheets () # Return the specified sheet object to form a list num = Book. nsheets # Return the number of sheets in the file Book. sheet_by_index (1) # Return the name of the sheet page of the specified index value Book. sheet_names () # Return the name Book of all sheet pages. sheet_by_name () # Return the sheet Page Object Book based on the name. sheet_loaded () # An error is returned when the specified index or name is used to determine whether there are any. name # Return the sheet name sheet. nrows # Returns the number of rows on the sheet page. ncols # Number of columns on the returned sheet page | column sheet. row (1) # obtain the specified row to form a Cell_lisy list [number: 20100805.0, text: 'o32 _ 201001_sp2 ', text: 'e class risk control asset category', text: 'Add N-subscribe to estimated asset (publicly available) ', empty: '', text: 'hu Yudong'] sheet. row_values (1) # list of specified rows [20100805.0, 'oss 32 _ 2010020.sp2 ', 'e class risk control asset categories', 'add N-net subscribe to estimated asset (public release) ', '', 'hu Yudong'] sheet. col (1) # obtain cell_listsheet.col_values (1) # listcell = sheet of the specified column. cell (1, 2) # obtain Ce based on location Ll object. Sheet. cell_value (1, 2) # obtain the value of the Cell Object Based on the location. Print (cell. value) # obtain the cell value # print the first column of each table for s in sheet: print (s. name) # obtain each sheet page for I in range (s. nrows): # s. nrows: the number of lines per sheet s. row (I): returns a list of each row.-1 indicates that the last value represents the text value print (s. row (I) [0]. value)

 Parse xml Module

Xml is a protocol for data exchange between different languages or programs. It is similar to json, but json is easier to use. However, in ancient times, in the dark era before json was born, you can only use xml. So far, many traditional companies, such as the financial industry, use xml as the main system interface.

Import xml. etree. elementTree as ETtree = ET. parse ("test. xml ") root = tree. getroot () print (root. tag) # tag> <data> header of this attribute for child in root: print (child. tag, child. attrib) # attributes in attrib <> constitute a dictionary for I in child: print (I. tag, I. text) # <> text content for year in root. iter ("year"): # iter () is equivalent to the attribute print (year. text) #*************************************** ** # modify xml for year in root. iter ("year"): new_year = int (year. text) + 1 year. text = str (new_year) # convert to string format to write year. set ("updated", "yes") # set format type updated yes indicates update tree. write ("test. xml ") # delete an xml node for country in root. findall ("country"): # The node is used to traverse all the country nodes under the root node. rank = country. find ("rank "). text # Check the rank node of each country and print text rank = int (rank) # convert str to int if rank <60: country. remove (country. find ("rank") # in this way, the rank of the node under country can also be removed directly from the large node tree of country. write ("new_test.xml ") # Write the generated file to the new file #******************************** * ****** new_xml = ET. element ("namelist") # name = ET. subElement (new_xml, "name", attrib = {"data": "2017-11"}) # generate a node nameage = ET under the outermost node. subElement (name, "age") # generate two more nodes under the name node, sexsex = ET. subElement (name, "sex") # sexage. text = "33" sex. text = "male" # set the number for age to be a character # You can add multiple nodes name2 = ET. subElement (new_xml, "name", attrib = {"data": "2018-11"}) # generate a node nameage = ET under the outermost node. subElement (name2, "age") # generate two more nodes under the name node, sexsex = ET. subElement (name2, "sex") # If text is not set, a tag age is displayed. text = "33 "#********************************** * ********** et = ET. elementTree (new_xml) # This step is to convert the format set above into the xml document et. write ("new_xml.xml", encoding = "utf8", xml_declaration = True) # write the file ET. dump (new_xml) # print the written file format

Configparser reads the configuration file and modifies the configuration file

 

Import configparser "[DEFAULT] ServerAliveInterval = 45 Compression = yesCompressionLevel = 9ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022ForwardX11 = no ******** * ****** [group2] k1 = v1 [group3] k1 = v1 "# parse conf = configparser. configParser () conf. read ("conf_new.ini") # Open the configuration file sec_list = conf. sections () # obtain the file's sections ["DEFAULT"] without printing s = conf ["bitbucket.org"] ["User"] # print the User text under the node section for v in conf [" topsecret.server.com "]: print (v) # print the node name under topsecret.server.com. The default node is also printed by default. # query opt = conf. options ("bitbucket.org") # Find the key value of the pair under the specified node print (opt) item = conf. items ("bitbucket.org") # returns the ancestor print (item) val = conf corresponding to the key value. get ("bitbucket.org", "compression") # group> [] key> k1: v1val = conf. getint ("topsecret.server.com", "Port") # obtain the int value print (val) # add or delete conf. read ("conf_new.ini") # Open the configuration file conf. remove_section ("group1") # Delete the node group1conf. add_section ("group3") # Add node group3conf. remove_option ("group3", "k1") # delete option first write group [] and then fill in keyprint (conf. has_section ("group1") # Check whether the conf group exists. set ("group3", "k1", "v1") # configure conf. write (open ("conf_new.ini", 'w') # The written file must be an open file. In other words, it is the input file handle.

 

  

 

  

 

 
 


 

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.