Summary of basic python operations

Source: Internet
Author: User

1. data Object persistence in some cases, you need to save the content of the data object to facilitate reading at the next time the program starts. This requires Object persistence, see the following example import pickle # create the test dictionary before_d = {} before_d [1] = "Name 1" before_d [2] = "Name 2" before_d [3] = "Name 3 "# pickle dump the dictionary fout = open (" dict1.dat ", "w") pickle. dump (before_d, fout, protocol = 0) fout. close () # pickle load the dictionary fin = open ("dict1.dat", "r") after_d = pickle. load (fin) fin. close () print (be Fore_d) # {1: 'name 1', 2: 'name 2', 3: 'name 3'} print (after_d) # {1: 'name 1', 2: 'name 2', 3: 'name 3'} we can see that the data object content is saved as a file, and some simple cache processing can be done, especially when writing small programs, it is very useful 2. target of Regular Expression replacement: replace overview.gif in the line string with other strings >>> line = '>> mo = re. compile (R '(? <= SRC =) "([\ w + \.] +) "', re. i) >>> mo. sub (R' "\ 1 ***" ', line)' >> mo. sub (r'replace _ str _ \ 1', line) '' </span> mo. sub (R' "testetstset" ', line)'  note: where \ 1 is the matched data, which can be referenced directly 3. in some cases, we need to traverse a directory to find a specific file list. it is very convenient to import OS fileList = [] rootdir = "/Tmp" for root, subFolders, files in OS. walk (rootdir): if '. svn 'in subFolders: subFolders. remove ('. svn ') # exclude a specific directory for file in files: if file. find (". t2t ")! =-1: # Find the file file_dir_path = OS with the specified extension. path. join (root, file) fileList. append (file_dir_path) print fileList 4. list by column (list sort) if each element in the list is a tuple, we need to sort it according to a column of the tuples, you can refer to the following method. In the following example, we sort the data in the 2nd and 3rd columns of the tuples in reverse order (reverse = True) >>> a = [('2017-03-17 ',' 2. 26 ', 6429600, '0. 0'), ('2017-03-16 ', '2. 26', 12036900, '-3.0'), ('2017-03-15 ', '2. 33 ', 15615500,'-19.1 ')] >>> print a [0] [0] 2011-03-17 >>> B = sorted (a, ke Y = lambda result: result [1], reverse = True) >>> print B [('2017-03-15 ', '2. 33 ', 15615500,'-19.1 '), ('2017-03-17', '2. 26 ', 6429600, '0. 0'), ('2017-03-16 ', '2. 26', 12036900, '-3.0')]> c = sorted (a, key = lambda result: result [2], reverse = True)> print c [('2014-03-15 ', '2. 33 ', 15615500,'-19.1 '), ('2017-03-16', '2. 26', 12036900, '-3.0'), ('2017-03-17 ', '2. 26 ', 6429600, '0. 0 ')] 5. list deduplication (list uniq) sometimes To delete repeated elements in the list, you must use the following methods> lst = [(1, 'ss'), (2, 'fsdf '), (1, 'sss'), (3, 'fd ')] >>> set (lst) set ([(2, 'fsdf'), (3, 'fd '), (1, 'sss')]) >>>>> lst = [1, 1, 3, 4, 4, 5, 6, 7, 6] >>> set (lst) set ([1, 3, 4, 5, 6, 7]) 6. dictionary sorting (dict sort) in general, we sort the data according to the dictionary key, but if we want to sort the data according to the value of the dictionary, use the following method> from operator import itemgetter> aa = {"a": "1", "sss": "2", "ffdf ": '5', "ffff2": '3' }>>> sort_aa = sorted (aa. items (), Key = itemgetter (1) >>> sort_aa [('A', '1'), ('ss', '2'), ('ffff2 ', '3'), ('ffdf ', '5')] 7. dictionary, list, String Conversion: Generate database connection string, convert from dictionary to string >>> params = {"server": "mpilgrim", "database": "master ", "uid": "sa", "pwd": "secret" }>>> ["% s = % s" % (k, v) for k, v in params. items ()] ['server = mpilgrim', 'uid = sa ', 'database = Master', 'pwd = secret'] >>> ";". join (["% s = % s" % (k, v) for k, v in pa Rams. items ()]) 'server = mpilgrim; uid = sa; database = master; pwd = secret the following example converts a string to a dictionary> a = 'server = mpilgrim; uid = sa; database = master; pwd = secret '>>> aa ={}>> for I in. split (';'): aa [I. split ('=', 1) [0] = I. split ('=', 1) [1]... >>> aa {'pwd': 'secret', 'database': 'master', 'uid': 'sa ', 'server': 'mpilgrim'} 8. the time object operation converts the time object to a string >>> import datetime >>> datetime. datetime. now (). strftime ("% Y-% m-% d % H: % M ") '2017-01-20 'time size comparison >>> import time >>> t1 = time. strptime ('1970-01-20 ', "% Y-% m-% d % H: % M") >>> t2 = time. strptime ('1970-01-20 ', "% Y-% m-% d % H: % M") >>> t1> t2 False >>> t1 <t2 True time difference calculation, calculated 8 hours ago >>> datetime. datetime. now (). strftime ("% Y-% m-% d % H: % M") '2017-01-20 '>>>> (datetime. datetime. now ()-datetime. timedelta (hours = 8 )). strftime ("% Y-% m-% d % H: % M") '2017-01-20' Converts a string to a time object >>> endtime = datetime. datetime. strptime ('20140901', "% Y % m % d") >>> type (endtime) <type 'datetime. datetime '>>>> print endtime 2010-07-01 00:00:00 >>> the number of seconds from 00:00:00 UTC to the present, format the output >>> import time >>> a = 1302153828 >>> time. strftime ("% Y-% m-% d % H: % M: % S", time. localtime (a) '2017-04-07 13:23:48 '9. command Line Parameter Parsing (getopt) usually requires different conditions when writing some daily O & M scripts, input different command line options to implement different functions. In Python, The getopt module is well implemented. Command Line Parameter Parsing, the following distance description. See the following program :#! /Usr/bin/env python #-*-coding: UTF-8-*-import sys, OS, getopt def usage (): print ''' Usage: analyse_stock.py [options...] options:-e: Exchange Name-c: User-Defined Category Name-f: Read stock info from file and save to db-d: delete from db by stock code-n: stock name-s: stock code-h: this help info test. py-s haha-n "HA Ha" ''' try: opts, args = getopt. getopt (sys. argv [1:], 'he: c: F: d: n: s: ') Doesn't getopt. getoptError: usage () sys. exit () if len (opts) = 0: usage () sys. exit () for opt, arg in opts: if opt in ('-H',' -- help'): usage () sys. exit () elif opt = '-d': print "del stock % s" % arg elif opt ='-F ': print "read file % s" % arg elif opt = '-C': print "user-defined % s" % arg elif opt ='-e ': print "Exchange Name % s" % arg elif opt = '-s': print "Stock code % s" % arg el If opt = '-N': print "Stock name % s" % arg sys. exit () Note: here we use the short format analysis string "he: c: f: d: n: s:". When an option only indicates the switch status, that is, when no additional parameter is provided, option characters are written to the analysis string. When the option is followed by an additional parameter, write the option character in the analysis string with a ":" So "he: c: f: d: n: s: "indicates that" h "is a switch option;" e: c: f: d: n: s: "indicates that these options should be followed by a parameter. 10. print formatted output 10.1. format the output string to capture the string output. In the following example, only the first three letters of the string are output >>>> str = "abcdefg" >>> print "%. 3 s "% str abc: output by fixed width. If not, use spaces to complete the output, in the following example, the output width is 10 >>> str = "abcdefg" >>> print "% 10 s" % str abcdefg, output according to fixed width >>> str = "abcdefg" >>> print "% 10.3 s" % str abc floating point type data bit reservation >>>> import fpformat >>> a = 0.0030000000005 >>> B = fpformat. fix (a, 6) >>> print B 0.003000 rounding the floating point number, mainly used in the round Function >>> from decimal import * >>> a = "2.26" >>> B = "2.29" >>> c = Decimal () -Decimal (B) >>> print c-0.03 >>> c/Decimal (a) * 100 Decimal ('-1.327433628318584070796460177') >>> decimal (str (round (c/Decimal (a) * 100, 2) Decimal ('-1.33') >>> 10.2. in some cases, different hexadecimal conversions are required. For more information, see the following example (% x hexadecimal, % d decimal, % o decimal) >>> num = 10 >>> print "Hex = % x, Dec = % d, Oct = % o" % (num, num, num) Hex = a, Dec = 10, oct = 12 11. python calls system commands or scripts to use OS. system () Calls system commands, and the output and return values cannot be obtained in the program >>> import OS >>> OS. system ('LS-l/proc/cpuinfo')> OS. system ("ls-l/proc/cpuinfo")-r -- 1 root 0 March 29 16:53/proc/cpuinfo 0 OS. popen () calls the system command. The command output can be obtained in the program, but the returned value cannot be obtained. >>> out = OS. popen ("ls-l/proc/cpuinfo")> print out. read ()-r -- 1 root 0 March 29 16:59/proc/cpuinfo >>> use commands. getstatusoutput () Calls system commands. The return values of command output and execution can be obtained in the program >>> import commands >>> commands. getstatusoutput ('ls/bin/ls') (0, '/bin/ls') >>> 12. python captures user Ctrl + C, Ctrl + D events sometimes, you need to capture user Keyboard Events in the program, such as ctrl + c exit, so as to better secure exit the program try: do_some_func () Comment t KeyboardInterrupt: print "User Press Ctrl + C, Exit" comment t EOFError: print "User Press Ctrl + D, Exit" 13. python reads and writes files to the list at a time, which is fast. track_file = "track_stock.conf" fd = open (track_file) content_list = fd when the file is small. readlines () fd. close () for line in content_list: print line reads data row by row, which is slow. It is applicable to the case where there is not enough memory to read the entire file (the file is too large) fd = open (file_path) fd. seek (0) title = fd. readline () keyword = fd. readline () uuid = fd. readline () fd. difference between write and writelines in close () Writing File Fd. write (str): writes str to a file. write () does not add a linefeed Fd after str. writelines (content): writes all content to a file. It is written as is without adding anything to the end of each line.

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.