Python string and file operations Common function Analysis _python

Source: Internet
Author: User
Tags throw exception

The example in this article analyzes the common functions of Python strings and file operations. Share to everyone for your reference. as follows:

#-*-Coding:utf-8-*-' Created on 2010-12-27 @author: Sumory ' ' Import itertools def a_containsanyof_b (seq,aset): "To determine if SEQ contains one or more items in Aset seq can be a string or list aset should be a string or list ' for item in Itertools.ifilter (ASET.__CONTAINS__,SEQ) 
  : Return True to return False def a_allin_b (seq,aset): ' Determine if all items in seq are in aset seq can be a string or list aset should be a string or list ' For the item in Seq:if item isn't in Aset:return False return True def a_containsall_b (seq,aset): "To determine whether SEQ is wrapped Contains all the items in the Aset seq can be a string or a list aset should be a string or any set object A,a.difference (b) is equivalent to A-set (b), that is, to return all elements in a that do not belong to B. Not set (aset). difference (SEQ) Import string #生成所有字符的可复用的字符串 Sumory_allchars=string.maketrans (",") def Makefilter ( Keep): "Returns a function that takes a source string as a parameter \ and returns a partial copy of the string \ This copy includes only the characters in Keep, keep must be an ordinary string \ Invocation Example: Makefilter (' ABCA ') (' A BCDEFGH Ijkal CBA ') \ retains the character in the following string, abc a CBA ' #按照sumory_allchars规则剔除sumory_allchars字符串中的keep里的字符 #这里得到kee P in Sumory_allchars's complement deleteChars=sumory_allchars.translate (Sumory_allchars,keep) #生成并返回需要的过滤函数 (as closure) def Realdelete (SOURSESTR): Return sourse Str.translate (Sumory_allchars,deletechars) return realdelete def list_removesame (list): ' Delete duplicates in list ' templist=[
  ] for C in List:if C. Templist:templist.append (c) return templist def re_indent (str,numberofspace): ' Indent ' divides string str by line-break and adds Numberofspace space\ to string ' spaces=numberofspace* ' before each sentence Lines=[spaces+line.strip
  () in Str.splitlines ()] return ' \ n '. Join (lines) def replace_strby_dict (soursestr,dict,marker= ' ", Safe=false): "Use the dictionary to replace the corresponding value of the marker package in the source string ' #如果safe为True, then do not replace if Safe:def lookup (w) if the dictionary is not found: return Dict.get (W,W.J Oin (marker*2)) #w. Join (MARKER*2) with the marker package W #如果safe为False, then the dictionary does not find the key throw exception \ #若将dict [W] for Dict.get (W) is not found when return none else : Def lookup (W): Return dict[w] #根据marker切分源字符串 splitparts=soursestr.split (marker) #取出切分后的奇数项 #因为切分后, List
 The marker wrapped item in the source string must be in the base position This is also true for strings such as #就算是 ' ' is one ' #分割后的第0项为空串, and the 1th is the Splitparts[1::2]=map (Lookup,splitparts[1::2]) return '. Join ( SplitParts def simply_replace_strby_dict (soursestr,dict,safe=true): "Replace the substring of $ tag in soursestr original string \ dict= {' By Dict content" Name ': ' sumory ', ' Else ': ' Default '} $$5-> $ $else-> default ${name} ' s method-> sumory ' s method ' sty Le=string.
  Template (SOURSESTR) #如果safe, in the dict can not find the words will not be replaced, still keep the original string if Safe:return Style.safe_substitute (dict) #false, can not find the throw exception Else:return Style.substitute (dict) ################################################## def scanner (object, Linehandler): "Use the Linehandler method to iterate through each item of object ' for line in Object:linehandler (line) def printfilelines (path): ' ' Read the file screen in path to print line by row ' Fileobject=open (path, ' R ') #open不用放到try里 try:for lines in Fileobject:print (Line.rstrip
  (' \ n ')] Finally:fileobject.close () def writelisttofile (path,ilist): Fileobject=open (Path, ' W ') Try:fileobject.writeli
NES (IList) Finally:    Fileobject.close () Import ZipFile def listzipfilesinfo (path): Z=zipfile. ZipFile (path, ' r ') try:for filename in z.namelist (): bytes=z.read (filename) print (' file:%s size:%s '% (uni Code (filename, ' cp936 '). Decode (' Utf-8 '), Len (bytes)) finally:z.close () Import Os,fnmatch def list_all_files (Root, 
  Patterns= ' * ', Single_level=false,yield_folders=false: ' Lists directories (or files under their subdirectories) ' #分割模式到列表 patterns=patterns.split (';') For path,subdirs,files in Os.walk (root): if Yield_folders:files.extend (subdirs) Files.sort () for Nam E in files:for Pat Patterns:if Fnmatch.fnmatch (name, Pat): Yield '/'. Join (Unicode (Os.path.joi 
  N (path,name), ' cp936 '). Split (' \ \) ') break if Single_level:break def swapextensions (root,before,after): If before[:1]!= '. ': before= '. ' +before Extensionlen=-len (before) if after[:1]!= '. ': after= '. ' +after for path,subdirs,files in Os.walk (root): for Oldfile in Files:if Oldfile[extensionlen:]==before:oldfile=os.path.join (Path,oldfile) newfile=oldfile[:extensionlen]+after Os.rename (Oldfile, NewFile)

I hope this article will help you with your Python programming.

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